Category: PHP

How to avoid PHP email injection hack:

An email injection hack occurs when an email form allows a hacker to add CC and/or BCC email addresses to the header of the email. This can occur if a form simply adds the from address field of a form to the header parameter of the mail function.

e.g.

$header="From: xxx@xxx.com" ;

Could be replaced with

$header="From: xxx@xxx.comrnBCC: xxx@xxx.comrnBCC: xxx@xxx.comrnBCC: xxx@xxx.com" ;

The $from variable below may be assigned the form parameter. You can see below that if a hacker added rnBCC: xxx@xxx.comrnBCC: xxx@xxx.comrnBCC: xxx@xxx.com” to the $from valiable, the email would be sent to all the email addresses.

$email  = trim($_POST['email');
$headers  = "From: $fromrn";
$headers .= "Content-type: text/html";
mail($to, $subject, $message, $headers);

The solution is to strip out any rn characters in code using the code below:

$email  = trim($_POST['email');

#ADD THIS LINE TO STRIP OUT ALL rn characters
$from = preg_replace('/[n|r.*/', '', $from);

$headers  = "From: $fromrn";
$headers .= "Content-type: text/html";
mail($to, $subject, $message, $headers);

Tags:

PHP

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 1

No votes so far! Be the first to rate this post.