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( [email protected]", "your feedback", $message, "From: $email" );

Where [email protected] 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( "/[\r\n]/", $usr ) || preg_match( "/[\r\n]/", $email ) ) {
    header("location : http://www.example.com/mail-error.php");

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  http://www.example.com/mail-error.php instead of sent mail.

Previous: PHP mail function
Next: PHP File Upload

Follow us on Facebook and Twitter for latest update.