- password_hash: documentation ( source)
- password_verify: documentation ( source)
<?php
// Challenge: make this terrible code safe
if((count($_POST) > 0) && (strlen($_POST['password']) == 0 || strlen($_POST['username']) == 0)){
echo "Please enter username and password".PHP_EOL;
exit();
}
try{
$pdo = new PDO('sqlite::memorytest:');
}
catch(PDOException $e){
echo $e->getMessage();
}
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
$pdo->exec("DROP TABLE IF EXISTS users");
$pdo->exec("CREATE TABLE users (username VARCHAR(255), password VARCHAR(255))");
$rootPassword = password_hash("secret", PASSWORD_DEFAULT);
$pdo->exec("INSERT INTO users (username, password) VALUES ('root', '$rootPassword');");
$statement = $pdo->prepare("SELECT password FROM users WHERE username = ? LIMIT 1");
if($statement->execute(array($_POST['username']))){
$row = $statement->fetchAll();
if(password_verify($_POST['password'], $row[0]['password'])){
echo "Access granted to $username!<br />\n";
exit();
}
else{
echo "Access denied for $username!<br>\n";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Challenge 4</title>
</head>
<body>
<form method="post">
<input type="text" name="username" placeholder="username" />
<input type="password" name="password" placeholder="password" />
<input type="submit" value="Submit" />
</form>
</body>
</html>