PHP and SQL injection attacks [2]
Magic Quotes
As mentioned above, SQL injection mainly submits unsafe data to the database to achieve the purpose of attack. In order to prevent SQL injection attacks, PHP comes with a function that can process the input string and perform preliminary security processing on the input at the lower level, that is, Magic Quotes. (php.ini magic_quotes_gpc). if magic_quotes_gpc
If the option is enabled, single quotes, double quotes and other characters in the input string will be automatically preceded by a backslash .
But Magic Quotes is not a very universal solution, it does not block all potentially dangerous characters, and on many servers Magic Quotes is not enabled. Therefore, we also need to use various other methods to prevent SQL injection.
Many databases provide this input data processing functionality natively. For example, PHP's MySQL operation function has a function called mysql_real_escape_string(), which can escape special characters and characters that may cause database operation errors.
refer to:
http://cn2.php.net/mysql_real_escape_string
If you are interested, you can read the comments below:)
Look at this code:
//If the Magic Quotes function is enabled
if (get_magic_quotes_gpc()) {
$name = stripslashes($name);
}else{
$name = mysql_real_escape_string($name);
}
mysql_query("SELECT * FROM users WHERE name='{$name}'");
Note that before we use the functions provided by the database, we must determine whether Magic Quotes is turned on, just like in the above example, otherwise it will be repeated twice. Processing will go wrong. If MQ is enabled, we need to remove the added to get the real data.
In addition to preprocessing the above string-form data, when storing Binary data in the database, you should also pay attention to preprocessing. Otherwise, the data may conflict with the storage format of the database itself, causing the database to crash, data records to be lost, or even the entire database to be lost. Some databases, such as PostgreSQL, provide a function pg_escape_bytea() specially used to encode binary data, which can encode the data similar to Base64.
like:
// for plain-text data use:
pg_escape_string($regular_strings);
// for binary data use:
pg_escape_bytea($binary_data);
In another case, we also need to use such a mechanism. That is, multi-byte languages such as Chinese, Japanese, etc. that are not supported by the database system itself. Some of them have ASCII ranges that overlap with binary data ranges.
However, encoding the data may cause queries like LIKE abc% to fail.