How to sanitze user input in PHP before mailing?

Matt Hampel picture Matt Hampel · Jun 28, 2009 · Viewed 33.6k times · Source

I have a simple PHP mailer script that takes values from a form submitted via POST and mails them to me:

<?php
$to = "[email protected]";

$name = $_POST['name'];
$message = $_POST['message'];
$email = $_POST['email'];

$body  =  "Person $name submitted a message: $message";
$subject = "A message has been submitted";

$headers = 'From: ' . $email;

mail($to, $subject, $body, $headers);

header("Location: http://example.com/thanks");
?>

How can I sanitize the input?

Answer

Haim Evgi picture Haim Evgi · Jun 28, 2009

Sanitize the post variable with filter_var().

Example here. Like:

echo filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);