I am a newbie on PHP but manage to create a working contact form. But then I got aware of Email Header Injection. How can I prevent this in best possible way? Don't want my form to be used to spam people.
This is my code:
<?php
if ($_POST["email"]<>'') {
$ToEmail = 'FixedEmail@domain.com';
$EmailSubject = 'Email Subject';
$mailheader = 'From: donotreply@domain.com' . "\r\n" .
'Reply-To:' .$_POST["email"]. "\r\n" .
'MIME-Version: 1.0'."\r\n".
'Content-Type: text/html; charset=utf-8'."\r\n".
'X-Mailer: PHP/' . phpversion();
$MESSAGE_BODY .= "<b>Navn:</b> ".$_POST["name"]."<br />";
$MESSAGE_BODY .= "<b>Telefon:</b> ".$_POST["telephone"]."<br />";
$MESSAGE_BODY .= "<b>Email:</b> ".$_POST["email"]."<br /><br />";
$MESSAGE_BODY .= "".nl2br($_POST["message"])."<br />";
mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure");
?>
Just Put the validation for email field as shown below:
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
if ($email === FALSE) {
echo 'Invalid email';
exit(1);
}
It validates your Email format which will not allow any kind of injected headers.