So, I'm expending this email submission form script for a client and saw something rather strange to my experience. As you can see below, the original programmer has sanitised the user input. Is this a good practice or does this makes sense at all?

// Build Message Body from Web Form Input
 foreach ($_POST as $Field=>$Value)
    $MsgBody .= "$Field: $Value\n";
 $MsgBody .= "\n" . @gethostbyaddr($_SERVER["REMOTE_ADDR"]) . "\n" .
 $MsgBody = htmlspecialchars($MsgBody, ENT_NOQUOTES);  //make safe

Thanks everyone!

1 Answer 1

  1. Fundamentally, yes, it is always a good idea to mistrust user input. If you have anything worth attacking, you will be attacked eventually. In this case, presumably the user input will eventually be redisplayed on a HTML page, so it makes sense to make sure it contains no malicious script code.
  2. It is a very bad idea to rely on the fact that the form content is sanitized before submission. Anybody can reverse engineer your script code and submit a message that hasn't been sanitized, therefore you absolutely need server-side validation as well. In other words, the escaping done in PHP is probably redundant because you have to repeat it anyway. It may still be a good solution for other reasons (e.g. because it shifts some computation from the server to the client and may save you money).

Note: security is always a property of an entire system. Anything I said about this snippet may be invalidated through the greater context you haven't shown!

  • In this case, presumably the user input will eventually be redisplayed on a HTML page ... A broader context would be that the input will not be shown anywhere on any page, so is this kind of escaping of any use at all.
    – Banago
    Commented Jul 3, 2011 at 13:18
  • you described it as an email form - if the person reading the email does so through a webmail interface, won't the input then be redisplayed on an HTML page? Commented Jul 3, 2011 at 13:28
  • @Kate, Well, that is supposed to be handled by the webmail software. It cannot relay on my sanitising, right?
    – Banago
    Commented Jul 3, 2011 at 22:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.