views:

817

answers:

1

What's considered the best practice these days for sanitizing data from a PHP email form?

I'm currently using something like this...

$msg = $_POST['msg'];
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$name = $_POST['name'];

$subject = "Message from the MY_WEBSITE website e-mail system";
$message = "From: " . $name . "\n";
$message .= "Email: " . $email . "\n\n";
$message .= $msg;
$headers = "From: " . $email . "\r\n" .
           "Reply-To: " . $email . "\r\n" .
           "X-Mailer: PHP/" . phpversion();

$mailSuccess = mail("[email protected]", $subject, $message, $headers);

Is it sufficient protection to simply filter the email field in this fashion? Can/should I harden the script more effectively to protect against spammers?

Thanks in advance!

[EDIT]Clarification, since the answers so far suggest that I've not explained myself well.

I'm not principally concerned with spambots getting hold of this script, but with anyone utilizing it to send illicit emails to any address other than [email protected]. This might include a bot, but could equally be a human defeating a CAPTCHA test.

What I'm looking for is PHP that will ensure that the email sent by the mail() method is not hijacked. This is probably a regex or filter or similar that simply strips certain characters. Thanks again.[/EDIT]

+1  A: 

I would do this:

  • Use CAPTCHA;
  • Fail to send if the subject or body includes any HTML tags whatsoever. Note: I didn't say strip them out. Just don't send the email and give an error message to the user why. There's no point sending yourself a filtered spam message. Just don't send it;
  • strip out any high or low characters (filter_vars() can do this);
  • limit the message to, say, 4000 characters (or some other appropriate limit that you pick);
  • fail if the message contains any URL that doesn't point to the current site;
  • arguably use some of the techniques from How do you stop scripters from slamming your website hundreds of times a second? to ensure there is a human sending the message.
cletus
> Best practice (imho) is not to send emails to email addresses supplied from an HTML form.Just to be clear on this point, the provided code doesn't -- or at least shouldn't -- send email to anyone other than the site owner. That address is hard-coded into the PHP ([email protected]). What I want to ensure is that no one hijacks the script, as with the classic \ncc:[email protected] to spam others.Thanks for the link! :c)
Wikiup
Sorry you're right: I misread it. Fixed now.
cletus