This question already has an answer here:
I have the following code in my php file:
session_start();
include "connect.php";
if (isset($_POST['email']) && isset($_POST['password'])) {
$email = htmlspecialchars(mysqli_real_escape_string($conn, $_POST['email']));
$password = htmlspecialchars(mysqli_real_escape_string($conn, $_POST['password']));
function process() {
include "connect.php";
if (isset($_POST['email']) && isset($_POST['password'])) {
$email = $_POST["email"];
$password = $_POST["password"];
}
mysqli_select_db($conn, "users");
$sql = "SELECT * FROM users WHERE email='$email' AND password='$password'";
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
if ($count >= 1) {
$_SESSION['id'] = $id;
$_SESSION['email'] = $email;
$_SESSION['password'] = $password;
header('location:index.php');
} else {
echo "Email/Password is incorrect";
}
}
if ($email != "" or $password != "") {
if (isset($_POST['submit'])) {
process();
} else {
echo "Error: " . mysql_error();
}
}
}
How would I go about preventing sql injection in my login page? I searched on the internet and most sites said I must use the mysqli_real_escape_string() function, but this did not seem to change things at all when I used the sql injection in my site again. please help :)
</div>
Use sql prepare :) http://www.php.net/manual/en/mysqli.prepare.php
From what I know this filters any sql injection
foreach($_POST as $key => $value) $_POST[$key] = mysqli_real_escape_string($value);
Most simple way, anyway i suggest of use prepare statements
First of all, - to avoid sql injection you need to filter any kind of user input. And simplest way to do it, is to use PDO
Yes, use PDO and prepare statements with try/catch blocks. When using prepare, each passes as a secure parameter, eliminating risk of injection.
You need to use prepared statements. I think following code snippet will give you some idea how to use it. please change according to your requirements
/* Create a prepared statement */
if($stmt = $mysqli -> prepare("SELECT * FROM users WHERE email=? AND password=?")) {
/* Bind parameters
s - string, b - blob, i - int, etc */
$stmt -> bind_param("ss", $email, $password);
/* Execute it */
$stmt -> execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
$_SESSION['id'] = $row['id'];
$_SESSION['email'] = $row['email'];
$_SESSION['password'] = $row['password'];
header('location:index.php');
/* Close statement */
$stmt -> close();
}
/* Close connection */
$mysqli -> close();
Docs Link: http://www.php.net/manual/en/mysqli.prepare.php
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://forum.codecall.net/topic/44392-php-5-mysqli-prepared-statements/