2

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" .
    $_SERVER["HTTP_USER_AGENT"];
 $MsgBody = htmlspecialchars($MsgBody, ENT_NOQUOTES);  //make safe

Thanks everyone!

Banago
  • 276
  • 1
  • 6

1 Answers1

3
  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!

Kilian Foth
  • 107,706
  • 45
  • 295
  • 310
  • 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 Jul 03 '11 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? – Kate Gregory Jul 03 '11 at 13:28
  • @Kate, Well, that is supposed to be handled by the webmail software. It cannot relay on my sanitising, right? – Banago Jul 03 '11 at 22:08