Protect your forms from hijackers May 1st, 2008 at 3:08 pm
The topic of protecting your forms from spammers looking to hijack your form mail is old and has been kicked around extensively . As a relatively new developer (2 years at the time of writing) I remember looking for a quick easy solution to protect form mails, so here it is.
A large portion of the spam found on the internet runs through ISPs in China. So not only are they doing a wonderful job at adding large amounts of lead to consumer products they are also responsible for hosting those wonderful messages that greet you in your inbox. One of the most notorious of these ISP’s is chinanet.
Because reputable hosting companies do not allow spam to go through their mail servers the spammers use your own php mail forms to send their wonderful greetings across the globe. Some of them are sophisticated enough to only send a small portion of mail through your form each day to keep the hosting company from flagging it. Once they find your unsecured form they will not let up.
They achieve this by injecting their own headers into your text fields to include a list of recipients and the message. The easiest way to prevent them from doing this is to check the fields for strings used to add these headers with a regular expression. What we are looking for are newline characters, hard returns, their coded equivalents, content-type, to:, cc: and bcc:.
We simply create a function that checks for these inputs and stops the script.
function fieldCheck($data) { if (eregi("(%0A|%0D|\n+|\r+)(content-type:|to:|cc:|bcc:)", $data)) { die ('Sorry, no spammers allowed.'); } }
Now for each field text field you have in your mail form you simply run the variable through this function. For example you will probably have at least two text fields for the user to enter their name and email address.
<form> Name: <input name="name" size="30" type="text" /> Email: <input name="email" size="30" type="text" /> <textarea name="msg"></textarea> </form>
Now before the mail() function is called we check for those characters with the fieldCheck() function we just created. Now if any of those characters present the script stops.
fieldCheck($name); fieldCheck($mail); // run your mail function
Don’t try to run the fieldCheck() function on the text area data. It will fail if a user hits a hard return for a new paragraph. You can check this data by creating another function that does not check for newlines and hard returns “%0A|%0D|\n+|\r+” and only check for the “content-type:|to:|cc:|bcc:”
So it would look like this …
function fieldCheck($data) { if (eregi("(%0A|%0D|\n+|\r+)", $data)) { die ('Sorry, no spammers allowed.');