I'm working on a game project (with Unity) that shall handle user credentials and other data. The game connects send requests to a php script and this script send requests to the database. After spending some days learning about sql injections and password handling, I came up with this approach. I am obviously still very naive with all this, but I would like to know if it is good or not. The first one is the script for creating a new user, and the second one is for login.
<?php
$servername = "localhost";
$username = "whatever";
$password = "whatever";
$dbname = "whatever";
try {
$db = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$salt = bin2hex(random_bytes(strlen($_POST["providedpass"])));
$hashpsw = hash('sha256', $_POST["providedpass"].$salt);
$name = $_POST["usrnm"];
$stmt = $db->prepare("INSERT INTO users (username, password, salt, level) VALUES (?,?,?,?)");
if ($stmt->execute(array($name,$hashpsw, $salt, 1))) {
echo "USER CREATED";
}
$db = null;
} catch (PDOException $e){
echo "Error: " . $e->getMessage();
}
?>
-
<?php
$servername = "localhost";
$username = "whatever";
$password = "whatever";
$dbname = "whatever";
try {
$db = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare("SELECT * FROM users WHERE username = ?");
$providedname= $_POST["usrnm"];
$stmt->execute(array($providedname));
while($row = $stmt->fetch(PDO::FETCH_OBJ)){
echo "FOUND USER";
$hashpsw = hash('sha256', $_POST["providedpass"].$row->salt);
if($hashpsw == $row->password) {
echo "CORRECT CREDENTIALS";
}
}
$db = null;
} catch (PDOException $e){
echo "Error: " . $e->getMessage();
}
?>