PHP secure mail

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

PHP secure mail

Need to write a code to send secure mail in php

If no preventive measures are taken while coding  a contact or feedback form in php, the code can be used by spammers to spam others. In this page, we will discuss how to write php mailing code so that it can not be compromised to spam.

A typical php code for mailing :  

A PHP script for sending email calls mail() function to deliver the email. The code looks like this :

mail(", "your feedback", $message, "From: $email" );

Where is the address of the webmaster and $message and $email are a message and email collected from the feedback or contact form.
Unless preventive measures are taken, it is possible for a spammer to inject additional headers into the email messages by placing lines like the following into the $email variable,,

When this code is executed, all the email addresses added to the list are going to receive mails, which is unintended and will solve the purpose of the spammers.

How to write a secure code for mailing with php:

if ( preg_match( "/[ ]/", $usr ) || preg_match( "/[ ]/", $email ) ) {
    header("location :");

Here, preg_match function will check of the user name (stored in $usrname) and email (stored in $email) contains any newline characters. If newline characters are found, then somebody trying to compromise the script to spam. In that case, the code will redirect to a page like instead of sent mail.