问题
Hello I have build a email form and I like to know if it is build in a secure way.
I have read the article How to Prevent Email Injection in Your PHP Form to Mail Scripts and applied it to my script. Now I like to know if the variable $to and $bcc are save.
function sendmail($to,$subject,$message,$bcc=NULL){
//Prevent Email Injection in Your PHP Form to Mail Scripts
if ( preg_match( "/[\r\n]/", $to ) || preg_match( "/[,]/", $to ) || preg_match( "/[\r\n]/", $bcc ) || preg_match( "/[,]/", $bcc ) ) {
return '<h1>Danger found: possible email Injection Hijacking</h1>';
return false;
}else{
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= 'From: No Reply <no-reply@domain.nl>' . "\r\n";
if(isset($bcc)) $headers .= 'Bcc: ' .$bcc."\r\n";
// Mail it
return mail($to, $subject, $message, $headers);
}
}
sendmail($_REQUEST['email'],'Subjectline', 'message','admin@domain.com');
回答1:
The vulnerability in mail comes from header injection. To prevent it, you can look for newlines in the header values, ie.:
"BCC: " . $email . "
X-OtherHeader: Foo-Bar
If $email
contains a newline, like:
webmaster@domain.com
TO: pro@hackerz.ru
You will get an extra TO header, which is potentially malicious. Header injection allows an attacker to send an email from your mailserver to anyone, essentially turning your mailserver into a spam server.
From the looks of it your current script is safe.
回答2:
Make sure there are only one e-mail replacing $str (string) using:
$str=str_replace(";","",$str);
$str=str_replace(",","",$str);
来源:https://stackoverflow.com/questions/19138093/what-is-the-best-way-to-prevent-email-injection-in-a-mailform