Method One: Password comparison pair
Thinking: First, the user entered the user name to query the database, get the user name in the database corresponding password, and then the query from the database password and user submitted over the password to carry out the match.
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 user name exists if ($arr [' Password ']== $pwd) {//Password pair echo "Login succeeded"; }else{ echo "Incorrect password input"; } }else { echo "This username does not exist"; } |
Analysis: In this case, the code is robust enough to prevent SQL injection attacks even in the case of Magic_quote_gpc=off. Because the attacker wants to log in successfully, they have to bypass the two, the first is to enter the username to exist, this step can construct an SQL statement (' or 1=1%23) directly bypass, but this way can not pass the second hurdle. Because the user is required to enter a correct password to pass, obviously, this has rejected the SQL injection attack.
Method Two: Use PDO's PDO::p Repare () preprocessing operations to prevent SQL injection attacks
Idea: Create a PDO object and use PDO preprocessing to prevent SQL injection attacks
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. Set Code $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. Take out the result $res = $pdoStatement->fetch (); if (empty ($res)) { echo "username or password entered incorrectly"; }else{ echo "Login succeeded"; } |