Formmailer safety

Posted on

Problem

I am currently working on a PHP-Formmailer. I`m completely new to PHP but I do have knowledge about HTML, CSS and Javascript. I would learn PHP starting with the basics and everything but I´ll be leaving the day after tomorrow so I would be very happy to see a quick solution 🙂

Mainly I´m concerned that the formmailer may be abused or that the e-mail will get spammed. Here´s what I did in HTML to prevent that:

  • Give the input-element a special type(like number or email)
  • Give the needed input-elements the value “required”
  • Make sure that search engines don´t find the website containing the form by adding

    <meta name="robots" content="noindex" /> 
    

to the header.

Now here is my PHP:

<?php


// ======= config:

$mailTo = 'myEmail';
$mailFrom = 'formmailer@homepage.com';
$mailSubject    = 'Formmailer of the homepage';
$returnPage = 'returnPage';
$returnErrorPage = 'errorPage';
$mailText = "";
// ======= configEND====

if(isset($_POST)) { 
   foreach($_POST as $name => $value) {
         $mailText .= $name . ": " . htmlspecialchars($value) . "n";
   }
}

 if(get_magic_quotes_gpc()) {
     $mailtext = stripslashes($mailtext);
 }

$mailSent = @mail($mailTo, $mailSubject, $mailText, "From: ".$mailFrom);

if($mailSent == TRUE) {  header("Location: " . $returnPage);}
else { header("Location: " . $returnErrorPage);}

exit();

?>

Do you think that this is safe enough for a small homepage? Am I using htmlspecialchars() correctly? Should I better use strip_tags()?

Solution

Your $mailTo, $mailSubject, and $mailFrom are all hard-coded values, which is good for security, because the mail headers are out of the client’s control. (Otherwise, you would have to watch out for a header-splitting attack.)

If anything, you’re overcompensating. htmlspecialchars() should play no role in the composition of plain-text e-mail. All it does is mangle the message body so that characters like & end up looking like &amp;. Not catastrophic, but incorrect and annoying.

The HTTP protocol is designed with the convention that GET and HEAD requests are free of side-effects, but POST requests may initiate actions. Therefore, you want to only send an e-mail if you received a POST request. However, your script is written such that a GET or HEAD request would send you an e-mail with an empty body. In a sense, you are committing a less-serious version of the Spider of Doom error. (Summary: someone’s website CMS was written such that a GET request could instruct the webserver to delete a page. Hilarity ensues when Googlebot starts crawling their site.) You should not rely on robots respecting <meta name="robots" content="noindex" /> to avoid that situation.

Leave a Reply

Your email address will not be published. Required fields are marked *