Home >Backend Development >PHP Tutorial >Detailed explanation of SQL injection vulnerabilities and prevention
The principle of SQL injection: append a piece of SQL code to the original SQL statement, construct a special SQL statement, and use the program's own permissions to implement the required operations.
Suppose there is a user table now:
uidusernamepwd
1adminadmin222
2custome123456
Now perform a login operation:
<?php $conn=mysqli_connect("localhost","root","root","test"); // 连接数据库test if (!$conn) { # code...判断链接是否成功 echo "连接失败!"; echo mysqli_connect_error(); exit(); } mysqli_query($conn,"set names utf8"); // 指定编码格式 $user = $_GET['user']; $pwd = $_GET['pwd']; $sql="select * from user where username = '{$user}' and pwd = '{$pwd}'"; // sql语句 $result=mysqli_query($conn,$sql); // 执行sql语句,将执行结果返回到结果集中 $row=mysqli_fetch_array($result); // 从结果集中取得一行作为数组 echo "<pre class="brush:php;toolbar:false">"; print_r($row); ?>
The above code performs a simple login operation. Execute this program in the browser: localhost/test/login.php?user=admin&pwd=admin222, executed The SQL statement is equivalent to: select * from user where username= 'admin' and pwd = 'admin222', and the execution result will be obtained.
If you request: localhost/test/login.php?user=admin&pwd=admin, there will be no query results because the password does not match the user name. That is, the SQL statement: select * from user where username= 'admin' and pwd = 'admin' cannot find the result. Then, if it is a SQL statement: select * from user where username= 'admin' and pwd = 'admin' or 1 = 1;? You can try it yourself, you can get this as follows:
uidusernamepwd
1adminadmin222
2custome123456
If accessed on the client: localhost/test/login What about .php?user=admin&pwd=admin%20or%201=1?
Directly bypassed the verification and obtained the admin user information in the database. This is a simple SQL injection.
SQL injection prevention:
(1) If it is an integer variable, use the intval() function or (int) to convert all incoming parameters into a numerical value.
(2) For character variables, use addslashes() to convert all ' (single quotes), " (double quotes), \ (backslashes) and (spaces) into characters containing backslashes .
(3) Escape or filter some special characters, such as %, etc.
Related recommendations:
. phpAbout deserialization object injection vulnerabilityShare five famous SQL injection vulnerability scanning toolsphp prevent SQL injection vulnerability codeThe above is the detailed content of Detailed explanation of SQL injection vulnerabilities and prevention. For more information, please follow other related articles on the PHP Chinese website!