This article simply uses an example to introduce a simple way to prevent SQL injection from PHP, there are friends who need to learn to refer to this article Oh.
Method One: The password comparison
Idea: First through the user input user name to query the database, get the user name in the database corresponding password, and then the database from the query to the password and the user submitted password to compare.
Code:
The code is as follows |
Copy Code |
$sql = "Select password from users where username= ' $name '"; $res =mysql_query ($sql, $conn); if ($arr =mysql_fetch_assoc ($res)) {//If the user name exists if ($arr [' Password ']== $pwd) {//Password pair echo "Login Successful"; }else{ echo "Password entered incorrectly"; } }else { echo "The user name does not exist"; } |
Analysis: In this case, the code is a lot more robust, even in the case of Magic_quote_gpc=off, can also prevent SQL injection attacks. Because the attacker wants to log in successfully, bypassing the two lanes, the first is to enter the user name to exist, this step can construct an SQL statement (' or 1=1%23) directly bypass, but this does not pass the second hurdle. Because the user is required to enter a correct password to pass, it is clear that this has rejected the SQL injection attack.
Method Two: PDO using PDO::p repare () preprocessing operation to prevent SQL injection attacks
Idea: Create a PDO object that can prevent SQL injection attacks by using PDO's preprocessing operations
Code:
The code is as follows |
Copy Code |
$name =$_get[' username ']; $pwd =$_get[' password ']; $sql = "SELECT * from Users where username=? and password=? "; 1. Create a PDO object $pdo =new PDO ("Mysql:host=localhost;port=3306;dbname=injection", "Root", ""); 2. Setting the Encoding $pdo->exec ("Set names ' UTF8 '"); 3. Preprocessing $sql statements $pdoStatement = $pdo->prepare ($sql); 4. Fill in the received username and password $pdoStatement->execute (Array ($name, $pwd)); 5. Remove the results $res = $pdoStatement->fetch (); if (empty ($res)) { echo "User name or password entered incorrectly"; }else{ echo "Login Successful"; } |
http://www.bkjia.com/PHPjc/629678.html www.bkjia.com true http://www.bkjia.com/PHPjc/629678.html techarticle This article simply uses an example to introduce a simple way to prevent SQL injection from PHP, there are friends who need to learn to refer to this article Oh. Method One: Password comparison thinking: The first ...