protecting php email form

I would like to know if what I have done would stop injection on my email form.

<?php 
if(isset($_POST['submit'])){
    $to = "[email protected]"; 
    $from = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL); 
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $subject = "Form submission";
    $subject2 = "Copy of your form submission";
    $message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
    $message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];

    $headers = "From:" . $from;
    $headers2 = "From:" . $to;
    mail($to,$subject,$message,$headers);
    mail($from,$subject2,$message2,$headers2); 
    echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";

}
?>

Upvotes: 1

Views: 107

Answers (2)

jbafford
jbafford

Reputation: 5668

The most important thing you can do to stop injection attacks is to properly escape content for its target context.

You've already done that by filtering the from email address, which in this case is sufficient to protected the email address from causing problems. In general, though, filtering is not sufficient to prevent injection attacks.

You also hard-code your subject, which is good. The documentation for mail() requires that the subject must satisfy RFC 2047, which is probably more reading than anyone actually wants to do. For these types of forms, it's probably best to use a subject that's defined in your code so that you can avoid any surprises, so you're covered there.

In general, you want to make sure the subject, and especially any headers that you add to the email, do not contain unexpected newlines, since that is the primary attack vector for mail(). Since your headers consist only of a sanitized and static email address, you should be good there as well.

Upvotes: 3

user557846
user557846

Reputation:

headers are the only injection point, and you only have one variable to take care of $from and you do that with filter_var

Upvotes: 3

Related Questions