PHP escaping $_POST data in sticky forms

Hi I have a sticky form which shows a user the form values if they submit the from and do not add required fields in the format:


<label for="name">Name (*required)</label>
<input type="text" name="name" id="name" value="<?php echo $_POST['name'] ?>" />

I have seen many examples of this on the web and the code works fine. However, is it secure enough and should i be escaping the output to the user?

I know it isn’t like a GET request where the url can be sent to someone and malicious code planted in the page for them.

However isn’t it a general security principle that any input taken from the user is filtered and escaped before it is shown?

Does anyone else do this?

Thanks
Steven

I think the safest thing to do in this scenario would be to validate all the $_POST data at the top of your script before you do anything with it, to make sure there is no undesirable code in any of the $_POST values.

For example - validate that $_POST[‘txtFirstName’] only contains characters for a valid first name and nothing else.

Like Kalon says, validating user input is always a good idea. A minimum validation before outputting the data might be strip_tags or [URL=“http://www.php.net/manual/en/function.htmlspecialchars.php”]htmlspecialchars. Or might be more complex and restrictive (like checking against an array of allowed values, or a regex, ecc).

There is no need to escape user input unless you’re using it in database queries. In that case, use mysql_real_escape_string to escape strings. Or use PDO.

I used the exact same method you have shown on the last form I created.

I would also like to know if there is a more secure method.

:slight_smile: