Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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!

share|improve this question
add comment

1 Answer

  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!

share|improve this answer
    
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 3 '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 3 '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 3 '11 at 22:08
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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