PHP Code:
/*
if (!preg_match("/^[_a-z0-9]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)){
$error .= "The e-mail address you entered is not valid. <br/>";
}
*/
if( ! filter_var( $email,FILTER_VALIDATE_EMAIL ) ){
$error .= "The e-mail address you entered is not valid. <br/>";
}
...
PHP Code:
/*
$from = 'From: ' . $name . ' <' . $email . '>';
*/
$from = "From: no-reply@example.com\r\n"; // <--change "example.com" to your domain name
----------------------------------
Also, I missed this earlier: that script is vulnerable to email header injection. You need to make sure $_POST['name'] contains no newlines:
PHP Code:
/*
if (!empty($_POST['name'])) {
$name = $_POST['name'];
}
*/
Two choices:
Quietly remove newlines and proceed as though nothing is wrong:
PHP Code:
if( ! empty( $_POST['name'] ) ){
// remove any carriage returns (which can be used to inject a new header)
// and any header names
// note this is the case-insensitive function, str_ireplace()
$name = str_ireplace( array( "\r","\n","%0a","%0d","Content-Type:","bcc:","to:","cc:" ),"",$_POST['name'] );
}
OR, reject the submission in its entirety if there is any evidence of this attack:
PHP Code:
if( ! empty( $_POST['name'] ) ){
// same as above...
$name = str_ireplace( array( "\r", "\n", "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:" ),"",$_POST['name'] );
// test if the filtered and unfiltered strings match.
// if they do not, that means the user put illegal characters in the "name" field.
if( $_POST['name'] !== $name ){
exit(); //<--don't even say anything. give them a blank page.
}
}
This is the safer (preferred) option.
It might seem unfriendly, but realistically, it is
almost impossible for an honest user to trigger this by accident.
Practically speaking, if this happens, it
is an attack, and you
do not want to allow them to continue.
----------------------------------
Coming back to the "From" issue, the main reason people put the visitor's email address in the "From" header is so they can click the [Reply] button when they receive the email.
The correct way to allow this is to use the "Reply-to" header:
PHP Code:
// after $from = "From: no-reply@example.com\r\n";
$from .="Reply-to: $name <$email>\r\n";
Bookmarks