PHP: Stopping E-mail Injections

The best way to stop e-mail injections is to validate the input.


function spamcheck($field)
//filter_var() sanitizes the e-mail
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
//filter_var() validates the e-mail
if(filter_var($field, FILTER_VALIDATE_EMAIL))
return TRUE;
return FALSE;

if (isset($_REQUEST[’email’]))
{//if “email” is filled out, proceed

//check if the email address is invalid
$mailcheck = spamcheck($_REQUEST[’email’]);
if ($mailcheck==FALSE)
echo “Invalid input”;
{//send email
$email = $_REQUEST[’email’] ;
$subject = $_REQUEST[‘subject’] ;
$message = $_REQUEST[‘message’] ;
mail(“”, “Subject: $subject”,
$message, “From: $email” );
echo “Thank you for using our mail form”;
{//if “email” is not filled out, display the form
echo “<form method=’post’ action=’mailform.php’>
Email: <input name=’email’ type=’text’ /><br />
Subject: <input name=’subject’ type=’text’ /><br />
Message:<br />
<textarea name=’message’ rows=’15’ cols=’40’>
</textarea><br />
<input type=’submit’ />


In the code above we use PHP filters to validate input:

  • The FILTER_SANITIZE_EMAIL filter removes all illegal e-mail characters from a string
  • The FILTER_VALIDATE_EMAIL filter validates value as an e-mail address

One thought on “PHP: Stopping E-mail Injections

What you think ? Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s