Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL prepared statement (PHP)

Tags:

php

mysql

I am trying to understand how SQL injection works, and how to prevent it. The HTML login page contains a form, as a table, with a username and password field, and a submit button. The PHP code, used with a mySQL database, looks like this:

$conn = mysqli_connect($Host, $User, $Password, $DbName);
if (!$conn) {
 echo "Database connection error.";
 exit;
}
$query = "SELECT user_name, password from visitors where user_name = '".$_POST['user_name']."';";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$user_pass = md5($_POST['pass_word']);
$user_name = $row['user_name'];
if(strcmp($user_pass,$row['password']) != 0) {
 echo "Login failed";
}

To prevent an SQL injection attack, I am trying to implement prepared statements, having had a look at the W3S website, and others. I assume I will need to replace

$query="SELECT user_name, password from visitors where user_name='".$_POST['user_name']."';";

with something like this:

$stmt = $conn->prepare("SELECT user_name, password from visitors where  user_name= ?");
if ($stmt->execute(array($_GET[‘user_name’]))) {
  while ($row = $stmt->fetch()) {
    $user_name = $row;
  }
} 

I am uncertain about the validity of the amendment. Also, in order to test whether the vulnerability of the system has been addressed, how would I be able to gain access to the system via the original, unmodified, code? I tried:

username: admin
password: ‘ or ‘1’=’1’ (and a number of other options too)
like image 722
cadebe Avatar asked Nov 09 '22 06:11

cadebe


1 Answers

The best way to prevent first, second and third order injections, I'd suggest you to use PDO as well as prepared statements while using the proper charset and disable "Emulated Prepared Statements". More information about how an SQL injection works and how PDO can prevent it can be found here.

like image 90
manniL Avatar answered Nov 15 '22 06:11

manniL