According to the PHP manual, in order to make code more portable, they recommend using something like the following for escaping data:
if (!get_magic_quotes_gpc()) {
$lastname = addslashes($_POST['lastname']);
} else {
$lastname = $_POST['lastname'];
}
I have other validation checks that I will be performing, but how secure is the above strictly in terms of escaping data? I also saw that magic quotes will be deprecated in PHP 6. How will that affect the above code? I would prefer not to have to rely on a database-specific escaping function like mysql_real_escape_string().
Magic quotes were a design error. Their use is incompatible with retainnig your sanity.
I prefer:
Don't write code for compatibility with inherently broken setups. Instead defend aginst their use by having your code FAIL FAST.
Magic quotes are inherently broken. They were meant to sanitize input to the PHP script, but without knowing how that input will be used it's impossible to sanitize correctly. If anything, you're better off checking if magic quotes are enabled, then calling stripslashes() on $_GET/$_POST/$_COOKIES/$_REQUEST, and then sanitizing your variables at the point where you're using it somewhere. E.g. urlencode() if you're using it in a URL, htmlentities() if you're printing it back to a web page, or using your database driver's escaping function if you're storing it to a database. Note those input arrays could contain sub-arrays so you might need to write a function can recurse into the sub-arrays to strip those slashes too.
The PHP man page on magic quotes agrees:
Put a requirement of PHP 5.2 or higher on your code and use the filter API. The
filter_*
functions access the raw input data directly (they don't ever touch$_POST
etc.) so they're completely unaffected bymagic_quotes_gpc
.Then this example:
Can become this:
I use the following code in the header file of my website to reverse the effects of magic_quotes:
Then I can write the rest of my code as if magic_quotes never existed.
"I would prefer not to have to rely on a database-specific escaping function like mysql_real_escape_string()"
Then use something like PDO. But you have to reverse the damage done by magic quotes anyway.
Your sample code is backwards, you should be doing the following:
Note that this leaves your input data in a 'raw' state exactly as the user typed it - no extra backslashes and potentially loaded with SQL Injection and XSRF attacks - and that's exactly what you want. Then, you make sure you always use one of the following:
echo
ing the variable into HTML, wrap it inhtmlentities()
mysql_real_escape_string()
as a minimum.echo
ing the variable into Javascritpt code, usejson_encode()
Joel Spolsky has some good starting advice in Making Wrong Code Look Wrong