Escaping input to the PHP mail() function →
Posted on January 15, 2012 in Development with 0 comments.
I recently built my email contact form on this website and thought I would share with you the method which I used to escape input to the PHP mail() function in order to avoid security vulnerabilities on your own contact form. You may think that the mail() function is a relatively safe function and data does not need to be cleaned, but quite the opposite is true. Lets quickly take a look as to why this is.
I am going to assume that your contact form on your website accepts a name, a persons email address and a message that they want to send to you. Lets also assume the contact form does a HTTP POST request to your page and we fetch the data that was sent with the following variables: $_POST['name'], $_POST['email'] and $_POST['message'].
Now our code looks something like this:
<?php
if ( isset( $_POST['submit'] ) ) {
$header = "From: " . $_POST['name'] . "<" . $_POST['email'] . ">\r\n";
mail( "you@yourdomain.com", "Message from our contact form", $_POST['message'], $headers );
}
?>
This is obviously a very simplified version of a script you would actually use. It doesn’t take into account validation etc. So, it looks pretty harmless doesn’t it? Well it’s not. And the reason for this is what if a user (read: spammer) entered the following in to the ‘email’ form field on your website
>\r\nBcc: spam@anotherdomain.com, spam2@anotherdomain.com, etc...
As you can see, a spammer could easily use your contact form and server to send out spam emails to anyone he/she pleases by manipulating your email form field.
How do you combat this behavior and secure your form? It’s actually pretty easy. You need to escape any data going into your email header variable. In our case it is the name and email field. Lets look at two functions (from Zend) that will do the escaping for us.
// Filter Name
function filter_name( $input ) {
$rules = array( "\r" => '', "\n" => '', "\t" => '', '"' => "'", '<' => '[', '>' => ']' );
$name = trim( strtr( $input, $rules ) );
return $name;
}
// Filter Email
function filter_email( $input ) {
$rules = array( "\r" => '', "\n" => '', "\t" => '', '"' => '', ',' => '', '<' => '', '>' => '' );
$email = strtr( $input, $rules );
return $email;
}
// Your $header line now becomes
$header = "From: " . filter_name( $_POST['name'] ) . "<" . filter_email( $_POST['email'] ) . ">\r\n";
Those are 2 very straight forward functions that will escape your form input and remove the risk of someone using your contact form for spamming. There are a few other functions that have been written that basically do the same thing, but I like the two above.
That’s about all there is to it. Simple but effective functions for escaping input to the PHP mail() function.







