PHP – Send Secure E-Mails to Stop E-Mail Injections

Created and implemented a PHP Filter Function which will Stop E-mail Injections.

To stop e-mail injections I have added an input validator that checks the “email” field when the form is submitted.

Filters are used in PHP to filter and validate external data (Like E-mail Address) which is coming from insecure sources.

Filter Function

function spam_email_check($email_field){
	// Sanitize Posted E-mail Address
  	$email_field = filter_var($email_field, FILTER_SANITIZE_EMAIL);
  	// Validate Posted E-mail Address
  	if(filter_var($email_field, FILTER_VALIDATE_EMAIL)){
    	return true;
    	return false;

Demo – Contact Us Form

// Display Form - Before Submit
if (empty($_POST["submit"])){?>
	<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
		<table width="460" border="0" cellpadding="1" cellspacing="2">
			<td width="88">Email ID:</td>
			<td width="387"><input type="text" name="email"></td>
			<td width="88">Subject:</td>
			<td width="387"><input type="text" name="subject"></td>
			<td width="88">Message:</td>
			<td width="387"><textarea rows="10" cols="40" name="message"></textarea></td>
			<td><input type="submit" name="submit" value="Send"></td>
}else{  // After Submit the Form
  	// Check "email" input field
  	if (!empty($_POST["email"])){
    	// Check "email address" is valid
    	$email_check = spam_email_check($_POST["email"]);
    	if($email_check == false){
    		echo "Invalid email address";
      		$sender_email_id = $_POST["email"]; 
			$subject = $_POST["subject"];
      		$message = $_POST["message"];      		
      		$message = wordwrap($message, 70);
      		// send mail
      		mail("",$subject,$message,"From: $sender_email_id\n");
      		echo "Thank you";

filter_var is used to filters a variable with a specified filter.

FILTER_SANITIZE_EMAIL is used to sanitizing and validating email address. It removes all the unwanted characters including blank space from the string. It also removes all the illegal e-mail characters from a string.

FILTER_VALIDATE_EMAIL is used to validates input value as e-mail address.


1 Comment on “PHP – Send Secure E-Mails to Stop E-Mail Injections

  1. You share interesting things here. I think that your blog can go viral easily, but you must give
    it initial boost and i know how to do it, just search in google – mundillo
    traffic increase

Leave a Reply

Your email address will not be published. Required fields are marked *