Thu, 17 Nov 2005

How To Send Mail Safely Using PHP

There are a growing number of spammers exploiting PHP scripts to send spam. Such scripts are often simple "Contact Us" forms which use PHP's mail() function. When using the mail() function, it is important to validate any input coming from the user before passing it to the mail() function.

For example, consider the following simple script.

<?php
$to        = 'info@example.com';
$subject   = 'Contact Us Submission';
$sender    = $_POST['sender'];
$message   = $_POST['message'];

$mailMessage = "The following message was received from $sender.\n\n$message";  
mail($to, $subject, $mailMessage, "From: $sender");

?>

Such a script looks fairly innocuous. The problem is that sender variable sent from the client is not sanitized. By manipulating the value sent in the sender variable, a malicous spammer could cause this script to send messages to anyone.

Here's an example of how such an attack might be carried out.

curl -d sender="spammer@example.com%0D%0ABcc: victim@example.com" \
-d message="Get a mortgage!" http://www.example.com/contact.php


Now, in addition to being sent to info@example.com, the message will also be sent to victim@example.com.

The solution to this problem is to either not set extra headers when using mail(), or to sanitize all data being sent in these headers. A simple example would be to strip out all whitespace from the sender's address.

$sender = preg_replace('~\s~', '', $_POST['sender']);

A more sophisticated approach might be to use PEAR's Mail_RFC822::parseAddressList() to validate the address.

tech » mail | Permanent Link

The state is that great fiction by which everyone tries to live at the expense of everyone else. - Frederic Bastiat