I was following a tutorial on creating a cms but the instructor used md5 for the passwords, I am trying to change it to use password_hash
instead. The password used in my sql database does use password_hash but I am getting confused as to how to verify it in my login page.
I've tried changing the md5 to password_hash
in the login page but this does not work and I've also tried password_verify
. I know these should be used but can't figure out where and what I should change.
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
?>
<html>
<head>
<title>CMS Tutorial</title>
<link rel="stylesheet" href="../assets/style.css"/>
</head>
<body>
<div class="container">
<a href="index.php" id="logo">CMS</a>
<br />
<ol>
<li><a href="add.php">Add Article</a></li>
<li><a href="delete.php">Delete Article</a></li>
<li><a href="logout.php">Logout</a></li>
</ol>
</div>
</body>
</html>
<?php
}else{
if (isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
//$password = md5($_POST['password']);
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
if (empty($username) or empty($password)){
$error = 'All fields are required!';
}else{
$query = $pdo->prepare("SELECT * FROM users WHERE user_name = ? AND user_password = ?");
$query->bindValue(1, $username);
$query->bindValue(2, $password);
$query->execute();
$num = $query->rowCount();
if ($num == 1) {
$_SESSION['logged_in'] = true;
header('Location: index.php');
exit();
//user entered correct details
}else{
//user entered false details
$error = 'Incorrect details!';
}
}
}
?>
<html>
<head>
<title>CMS Tutorial</title>
<link rel="stylesheet" href="../assets/style.css"/>
</head>
<body>
<div class="container">
<a href="index.php" id="logo">CMS</a>
<br /><br />
<?php if (isset($error)) { ?>
<small style="color:#aa0000"><?php echo $error; ?></small>
<br /><br />
<?php } ?>
<form action="index.php" method="post" autocomplete="off">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Login" />
</form>
</div>
</body>
<html>
<?php
}
?>
At the moment I am just getting the
"incorrect details" error
that I have created and if I use password_verify I get the
"all fields are required error"