Consider file a.php:
<?php
echo $_GET['a'];
?>
a.php?a=abcd' prints abcd\'.
I think PHP auto escape quotes, but I couldn't find a document about this.
Is it true? Because I want to make sure - I'm quite lazy, so I didn't prevent SQL injection in my PHP source code...
It depends on whether
magic_quotes_gpcinOnor not on yourphp.iniconfiguration file.This configuration directive was introduced to help developers secure themselves against SQL injection attacks. If you don't know what they are, I suggest you read the Wikipedia entry very carefully.
The thing is, relying only on
magic_quotesis insecure and unpredictable, and this feature will also be removed in future PHP versions. The best way to secure against SQL injection is to either use prepared statements (with PDO or MySQLi) or use the specific escaping function for your database:PDO::quote()mysql_escape_string()or better yetmysql_real_escape_string()However, if
magic_quotesis on and you try to escape your input data chances are you will get a double escaped string (which is not good), to counteract this we usually detect ifmagic_quotesisOnand, if it is, remove the added slashes viastripslashes().Some do this before calling the database escaping function / method, but personally I prefer to do it upon page load since this will make the data much more consistent and less prone to errors. If you're using PHP 5.3+ the following snippet should disable
magic_quotes:If you are running an older version of PHP, the PHP Manual has a fairly good snippet too: