I Need Help With Preventing Contact Form Email Injection

Hi, I really don’t know much about php code and need help. Could you tell me what I need to add to this email form php code to stop spammers from email header injection? My hosting account recently was sending spam emails that I did not send and I thought this might be the problem. Thanks.

Here is what I have now:

[php]

<?php $to = "[email protected]"; $subject = "Pottery Question"; $email = $_REQUEST['email'] ; $name = $_REQUEST['name'] ; $questions = $_REQUEST['questions'] ; $spam = $_REQUEST['spamcheck'] ; { if ($spam == 4){ $message .= "Name: \n"; $message .= $name; $message .= "\n"; $message .= "\n"; $message .= "Email: \n"; $message .= $email; $message .= "\n"; $message .= "\n"; $message .= "Questions: \n"; $message .= $questions; $headers = "From: $email"; $sent = mail($to, $subject, $message, $headers) ; if($sent) {print "Your message was sent successfully"; } else {print "We encountered an error sending your mail"; } } else {header( "Location: http://www.go.away" ); die();} } ?>[/php]

A few things right off the bat, don’t use $_REQUEST. You want to use the actual array that is passing the data, most likely $_POST.

If the only header you are using is the from attribute, just directly add that. Also, validate the incoming data. Anything supplied by a user should not be trusted!

Things like
[php]filter_var($address, FILTER_VALIDATE_EMAIL)[/php]

Will tell you if the email is valid. Passing data from one variable to another, is not needed and is just extra code. The only time this is acceptable, is when the new variable modifies the data and you still need an original copy.

Here is a bit more information for you to look at: Preventing Header injection

The filter_var is better than the regular expressions in the link, but it is still good information. Also, change your email password. If you are not using a strong password, do so. My average password is a minimum of 16 characters and is nothing but random letters, numbers, and special characters.

Sponsor our Newsletter | Privacy Policy | Terms of Service