Note on PHP contact form
I recently came across a mechanism by which someone could take over a "Contact Form" written in PHP and use it to send spam. They do this by over filling certain fields in a hope that they can add more parameters to the mail() function.
The mail() function in PHP has the following parameters:
mail( string to, string subject, string message [, string additional_headers [, string additional_parameters]] )
The additional headers parameter is used to convey anything else you can find in an email, these are things like CC and BCC. It is the BCC header that the spammer hopes to take over, adding his own set of addresses so that it looks as though you have been sending spam. He does this in one of two ways:
- By adding PHP code to the message box so that when the mail function is called there will be extra headers in the additional headers parameter.
- By adding code to the address bar of the browser in such a way that the form is changed. He might change one of the text boxes to a text area and use this new area to add the headers.
By doing either of these things he hopes to add another carage return character and adding a BCC field after that.
There are a number of ways to combat this.
The first is to use the strip_tags() method. This will remove any PHP or HTML tags from any string. The strip_tags() method has two parameters. The first is the string that you are supplying to the method, the second is any HTML tags that you do actually want to be kept. You can use the following value to allow a number of HTML tags at once.
$allowedTags = '<p><br><b><i><strong><u><h1><h2><h3><h4><h5><h6>'
This will allow most of the formatting tags to be passed through. The main use of this function is to strip out any PHP tags.
You can also use the str_replace() method to do more or less the same thing. This method takes three arguments. The first is what to look for in a string, also called the needle. The second is what to replace it with, also called the haystack, and the third is the string itself. If you want to pass more than one needle in a single function call by using an array of values, as in the following:
$deleteAllTags=array('<','>','','/','=','+');
Using these two methods in conjunction should stop most stuff getting through. You should be checking all of the fields to validity anyway, and by doing this you stop most of these attacks getting in.
The second method is to always use POST methods to send the data in the form to the server. This way the form will ignore anything written in the address bar. As it is bad practice to use GET methods in any form you can usually get around this method without even trying.
The contact us form on my website should stop this sort of thing. I have tested it as well as I can. If you want the code then contact me! If you have any other comments or questions then let me know.

Discussion Area - Leave a Comment