Perl Programming Page 4 - Perl 101: The email form |
As I mentioned earlier, the regular expression we created on the previous page was pretty basic (you may well be wondering what a complex regexe looks like, but try not to for now). Now that we've covered the basics, it's time to improve on our regex. unless ($name =~ /^[\w ]/) { print "Oops you entered your name incorrectly - please go back and check it<br>"; die; } This works fine for filtering the users name, but what about his email address? Email addresses contain periods and at symbols, so we'll need to allow for those. In the previous section we talked about how characters inside the square brackets are alternates. To allow @ and . we simply add them to what we already have: unless ($email =~ /^[\w @.]/) { print "Oops you entered your email incorrectly - please go back and check it<br>"; die; } And for the actual message we'll again limit it to letters, number, underscores and spaces: unless ($message =~ /^[\w ]/) { print "Sorry, you can only use letters, numbers, underscores and spaces in your message<br>"; die; } Putting It All Together So finally we have a complete script, which now looks like this: #!/usr/bin/perl use CGI; $q = new CGI; $sendmailpath = "/usr/lib/sendmail"; $myemail = "pete\@p-smith.co.uk"; $name = $q->param("name"); $email = $q->param("email"); $message = $q->param("message"); print "Content-type:text/html\n\n"; unless ($name =~ /^[\w ]/) { print "Oops you entered your name incorrectly - please go back and check it<br>"; die; } unless ($email =~ /^[\w @.]/) { print "Oops you entered your email incorrectly - please go back and check it<br>"; die; } unless ($name =~ /^[\w ]/) { print "Oops you entered your message incorrectly - please go back and check it<br>"; die; } open(MAIL, "| $sendmailpath -t"); print MAIL "To: $myemail"; print MAIL "Reply: $email"; print MAIL "Subject:Webmail $name"; print MAIL "\n"; print MAIL "$message"; close MAIL; print "<html><body>Thank you for your comments, you mail has been sent"; Upload it as you did earlier then go back to your hHTML form, fill it in, and submit it. If all goes well you will receive the 'Thank You' message. If not, it's time to check through your script for typos again. Wait a few minutes then check your email. You should have received the message you sent from the form.
blog comments powered by Disqus |
|
|
|
|
|
|
|