Friday, March 20, 2015

(Secure) PHP Login System (Protected Against SQL-Injections)

In a previous post I presented a login system with PHP. Due to the usage of the simple queries of the mysql class there it was vulnerable against SQL-injections though. Today I want to fix this by using the class mysqli and prepared statements, which were introduced in a previous post.
Since the principle of the login system stayed the same and the prepared statements were explained in the linked post, here simply the code:

register.php (http://bloggeroliver.bplaced.net/PHPExamples/LoginV2/register.php):

<?php
$conn = new mysqli("db4free.net", "csharptricks", "12345678", "csharptricks");

$username = $_POST["username"];
$password = $_POST["password"];
$hashedpw = md5($password);

$stmt = $conn->prepare("SELECT username FROM Users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->store_result();

if ($stmt->num_rows > 0) {
     echo "Existing";
}
else {
     $stmt = $conn->prepare("INSERT INTO Users (username, password) VALUES (?, ?);");
     $stmt->bind_param("ss", $username, $hashedpw);
     $stmt->execute();
     echo "Success";
}
?>

login.php (http://bloggeroliver.bplaced.net/PHPExamples/LoginV2/login.php):

<?php
session_start();

$conn = new mysqli("db4free.net", "csharptricks", "12345678", "csharptricks");

$username = $_POST["username"];
$password = $_POST["password"];
$hashedpw = md5($password);

$stmt = $conn->prepare("SELECT username, password FROM Users WHERE username = ? LIMIT 1");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->bind_result($output1, $output2);
$row = $stmt->fetch();

if($output2 == $hashedpw) {
    $_SESSION["username"] = $username;
    echo "LoginGood";
}
else {
    echo "LoginBad";
}
?>

Since the interface to the outside stayed the same, of course the C# code for the login application from the previous post can also be reused.

No comments:

Post a Comment