phppostgetaddslashes

Should I escape characters in my GET and POST requests?


I have just read that PHP escapes incoming GET and POST requests on its own for some time. Double escaping does no good. Should I escape the strings at all?

For example I process a simple input like this:

$contact = mysqli_real_escape_string($dbLink, strip_tags($_POST['contact']));

Later, when saved and retrieved from the database I fill the input with last values, like:

echo '<input type="text" class="form-control" id="inputContact" name="contact" value="'.$contact.'">'.PHP_EOL;

When someone enters quotes in the field, it returns something like this, which destroys the form:

<input type="text" class="form-control" id="inputContact" name="contact" value="0900 123 456, jozefmat" ejkasdfadsf"="">

Solution

  • I have just read that PHP escapes incoming GET and POST requests on its own for some time

    This is magic quotes, they were always ineffective and more trouble then they were worth. They have been deprecated and modern versions of PHP do not support them at all.

    Should I escape the strings at all?

    Yes. You should perform suitable sanitization of untrusted data (either via escaping, white list filtering or some other suitable means) as is applicable for the place you are putting the data (which is different depending on if you are inserting it into a database query (search for SQL injection), an HTML document (search for XSS or Cross-Site Scripting) or somewhere else).

    As you have noticed, the options you have available to do even within an HTML document vary - what is suitable for "Inside an element" is not always suitable for "Inside an attribute value" or "Inside a script element".