Security checks on contact forms

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

PHP contact forms are very common.  But you should make some security checks before sending the contents out via mail.  Or better yet, use some third party forms or WordPress form plugins.

But if you are using straight PHP, you should at least consider doing the following checks.  Suppose you have a typical contact form…

typical contact form

typical contact form

With typical HTML …

contact form HTML

contact form HTML

Except that we have added an extra hidden input field with name “token” with some arbitrary value of “MyFormPage”.  And that we have added a session variable $_SESSION[‘FORMTOKEN’] with value ‘MY_CONTACT_FORM’.

As a first pass at this implementation for now, we are just using a hard-coded form token value of “MY_CONTACT_FORM” which a hacker can potentially guess or gain access to the source code.  For better security, you should use a randomly generated form token instead (example in another tutorial).

The session_start() is needed at the top of every PHP page in order to use sessions.

So when this form submits to sendmail.php, the sendmail.php file will check for the correct session value and the correct submitted hidden input token…

check session and hidden variable

check session and hidden variable

This ensure that before sendmail.php does anything, it make sure that it came from our form with those values.  It also prevents people from navigating to the sendmail.php URL directly and invoking the script.

We can further check where the form submission was coming from by checking the $_SERVER[‘HTTP_REFEER’] and make sure it is from our HTML form URL (see code above).

Next we prevent form hijacking by making sure there are no \r and \n characters in the email and name field (see code below).  Then we make sure that the email address submitted was correct using the PHP filter_var() function with the FILTER_VALIDATE_EMAIL filter (tutorial here)

prevent form hijacking and sanitize fields

prevent form hijacking and sanitize fields

Using filter_var() we sanitize all other field inputs as shown above.

If all these checks pass, you can send the mail using phpmailer (preferred) or with the PHP mail() function.