PHP protecting itself from SQL injections?

2019-03-06 07:04发布

问题:

When I send ");-- from an input field to my localhost PHP server, it AUTOMATICALLY converts it to

\");--

It seems great, except that I don't know how trustworthy this behavior is. Although it seems to avoid SQL injections, my development environment is not the same as the production environment and I'm afraid that the production environment may not have this sort of protection automatically activated...

Why does PHP does this(convert the input without having to use mysql_real_escape_string)? Does it always do it or only with certain extensions? Is it safe to rely on this behavior to prevent SQL injections?

回答1:

It seems that you have Magic Quotes enabled. But you better disable this option or revert them. mysql_real_escape_string is more secure.



回答2:

This "feature" of PHP is known as "magic quotes". As 'magic' as they may be, it is extremely bad practice to use them, as they do little more than give a false sense of security. Thankfully they have been removed from PHP 6 (in development).

A more detailed list of criticisms can be found in this Wikipedia article.

The PHP manual describes various ways to disable magic quotes.



回答3:

You might want to get into talking to the database using an abstraction layer like Zend_Db. For example, if you create a select statement by instantiating a Zend_Db_Select, it would look like this:

//$_GET['thing'] is automatically escaped 
$select = $zdb->select()->from('things')->where('name = ?',$_GET['thing']);
$result = $zdb->fetchRow($select->__toString());//__toString generates a really pretty, vendor independent query

//a plain vanilla query would look like this:
$result = $zdb->fetchRow('select * from things where name = ?', $zdb->quote($_GET['thing']);


回答4:

You have Magic Quotes turned on. The PHP group officially deprecated this function strongly, and strongly discourages relying on it. Ways to disable magic quotes at runtime don't always work, weather you use .htaccess or ini_set() in the script. Calling stripslashes all the time can also become pretty messy.

More details: http://ca3.php.net/magic_quotes