I have a simple PHP mailer script that takes values from a form submitted via POST and mails them to me:
<?php
$to = "me@example.com";
$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?
You can use the code from
artlung
's answer above to validate email..I use this kind of code to prevent header injection ..
The
mail()
's header filtering above is too strict, since some users may be using the filtered strings in their message without any intention to hijack your email form, so redirect it to a page that is explaining what kind of strings that is not allowed in the form or explain it on your form page.As others have noted,
filter_var
is great. If it's not available, add this to your toolchest.The
$headers
variable is particularly bad security-wise. It can be appended to and cause spoofed headers to be added. This post called Email Injection discusses it pretty well.filter_var i
s great, but another way to assure that something is an email address and not something bad is to use anisMail()
function. Here's one:So to use this, you could do:
In terms of manual validation, limiting the length using
substr()
, runningstrip_tags()
and otherwise limiting what can be put in.Sanitize the post variable with
filter_var()
.Example here. Like:
Since you're not building an SQL query or anything here, the only relevant validation that I can see for those inputs is an email validation for $_POST["email"], and maybe an alphanumeric filter on the other fields if you really want to limit the scope of what the message can contain.
To filter the email address, simply use filter_var:
As per Frank Farmer's suggestion, you can also filter out newlines in the email subject:
You need to remove any newlines from input provided by users in $headers, which gets passed to mail() ($email in your case)! See Email injection.
PHP should take care of sanitizing $to and $subject, but there are versions of PHP with bugs (Affected are PHP 4 <= 4.4.6 and PHP 5 <= 5.2.1, see MOPB-34-2007).