By inserting SQL commands into Web forms to submit or input the query string of domain names or page requests, the server is finally tricked into executing malicious SQL commands.
Example
1: The entered username must be a combination of letters, numbers and underscores, and the username must be between 8 and 20 characters long:
if (preg_match("/^\w{8,20}$/", $_GET['username'], $matches))
{
$result = mysqli_query($conn, "SELECT * FROM users
WHERE username=$matches[0]");
}
else
{
echo "username 输入异常";
}
2. The SQL situation that occurs when special characters are not filtered:
// 设定$name 中插入了我们不需要的SQL语句
$name = "Qadir'; DELETE FROM users;";
mysqli_query($conn, "SELECT * FROM users WHERE name='{$name}'");
Summary: In the above injection statement, we did not filter
$name
the variable of , and inserted the SQL statement we do not need into $name, which will delete all data in the users table.
Prevent SQL Injection
//获取magic_quotes_gpc配置
if (get_magic_quotes_gpc())
{
//获取反转义的字符串
$name = stripslashes($name);
}
$name = mysqli_real_escape_string($conn, $name);
mysqli_query($conn, "SELECT * FROM users WHERE name='{$name}'");
The MySQL extension for PHP provides
mysqli_real_escape_string()
functions to escape special input characters.
Injection in Like Statements
When querying like, if the value entered by the user is
"_"
sum"%"
, this situation will occur: the user only wants to query"abcd_"
, but the query result has"abcd_"、"abcde"、"abcdf"
etc.; when the user wants to query "30%" (Note: 30%) Problems can also arise. In a PHP script we can useaddcslashes()
functions to handle the above situations, as in the following example:
//addcslashes() 函数在指定的字符前添加反斜杠。
$sub = addcslashes(mysqli_real_escape_string($conn, "%something_"), "%_");
// $sub == \%something\_
mysqli_query($conn, "SELECT * FROM messages WHERE subject LIKE '{$sub}%'");