Changing from md5 to password_hash - php

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">
CMS
<br />
<ol>
<li>Add Article</li>
<li>Delete Article</li>
<li>Logout</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">
CMS
<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"

To check the password you must use password_verify() function, instead of password_hash().
Some time ago I wrote a canonical example, Authenticating a user using PDO and password_verify().
As you can see, the code is extremely simple: you just need to select the password and then compare it using password_verify()
$stmt = $pdo->prepare("SELECT * FROM users WHERE user_name = ?");
$stmt->execute([$_POST['username']]);
$user = $stmt->fetch();
if ($user && password_verify($_POST['password'], $user['password']))
{
$_SESSION['logged_in'] = true;
header('Location: index.php');
exit();
}else{
$error = 'Incorrect details!';
}

Related

Trying to create a CMS but having trouble with the login

CMS Tutorial and the stage I'm up to https://youtu.be/QNxU3Qa6QZs?t=1817
When I enter the wrong details it says that they are incorrect like it should but when I enter the correct details it is meant to login like in the video it shows a blank page but mine just refreshes the page and shows the login form again. I would really appreciate if anyone can help me out, thanks.
<?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">
CMS
<br>
<ol>
<li>Add Article</li>
<li>Delete Article</li>
<li>Logout</li>
</ol>
</div>
</body>
</html>
<?php
} else {
if (isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
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();
} else {
$error = 'Incorrect Details!';
}
}
}
?>
<html>
<head>
<title>CMS Tutorial</title>
<link rel="stylesheet" href="../assets/style.css">
</head>
<body>
<div class="container">
CMS
<br> <br>
<?php if (isset($error)) { ?>
<small style="color:#aa0000;"><?php echo $error; ?> </small>
<br> <br>
<?php } ?>
<form action="index.php" method="post">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<input type="submit" value="Login">
</form>
</div>
</body>
</html>
<?php
}
?>
See this on line 6?
$SESSION['logged_in']
The PHP super global is: $_SESSION. Add an underscore there and it should work.

PHP PDO login Username and Password not found

So i followed a tutorial that shows how to login,
But i made a username and password in my phpmyadmin, But everytime when i try to login it says: Username or Password not found this is the code;
<!--Begin webshop WOOOH-->
<?php
session_start();
//DB configuration Constants
include("class.php");
//PDO Database Connection
try {
$databaseConnection = new PDO('mysql:host='._HOST_NAME_.';dbname='._DATABASE_NAME_, _USER_NAME_, _DB_PASSWORD);
$databaseConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
if(isset($_POST['submit'])){
$errMsg = '';
//username and password sent from Form
$username = trim($_POST['username']);
$password = trim($_POST['password']);
if($username == '')
$errMsg .= 'You must enter your Username<br>';
if($password == '')
$errMsg .= 'You must enter your Password<br>';
if($errMsg == ''){
$records = $databaseConnection->prepare('SELECT id,username,password FROM tbl_users WHERE username = :username');
$records->bindParam(':username', $username);
$records->execute();
$results = $records->fetch(PDO::FETCH_ASSOC);
if(count($results) > 0 && password_verify($password, $results['password'])){
$_SESSION['username'] = $results['username'];
header('location:dashboard.php');
exit;
}else{
$errMsg .= 'Username and Password are not found<br>';
}
}
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/reset.css">
<title>Webshop 2016</title>
</head>
<body>
<div id="wrapper">
<div id="header">
<ul>
<li>Info</li>
<li>Login</li>
<li>Webshop</li>
<li>Home</li>
</ul>
</div>
<!--Main content!-->
<div id="content">
<div align="center">
<div style="width:300px; border: solid 1px #006D9C; " align="left">
<?php
if(isset($errMsg)){
echo '<div style="color:#FF0000;text-align:center;font-size:12px;">'.$errMsg.'</div>';
}
?>
<div style="background-color:#006D9C; color:#FFFFFF; padding:3px;"><b>Login</b></div>
<div style="margin:30px">
<form action="" method="post">
<label>Username :</label><input type="text" name="username" class="box"/><br /><br />
<label>Password :</label><input type="password" name="password" class="box" /><br/><br />
<input type="submit" name='submit' value="Submit" class='submit'/><br />
</form>
</div>
</div>
</div>
</div>
<div id="footer">
Footer
</div>
</div>
</body>
</html>
This is the class.php (the connection file)
<?php
define('_HOST_NAME_', 'localhost');
define('_USER_NAME_', 'root');
define('_DB_PASSWORD', '####');
define('_DATABASE_NAME_', 'ws_webshop');
//PDO Database Connection
try {
$databaseConnection = new PDO('mysql:host='._HOST_NAME_.';dbname='._DATABASE_NAME_, _USER_NAME_, _DB_PASSWORD);
$databaseConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
Does anyone see the problem?
the user and pass is demo / demo but he says theres no Username or password found...
From the docs:
Returns TRUE if the password and hash match, or FALSE otherwise.
If you did not use password_hash() to insert the password in the database your check using password_verify() attempt here:
if(count($results) > 0 && password_verify($password, $results['password'])){
will always fail because the function expects a plain password to compare against the hashed value of the password. for more insight on PHP's password functions read this post.
In addition you may find yourself wanting to limit passwords and you really shouldn't do that.

$_SESSION doesn't start

When user is logged in nothing is displayed on the screen(Error-reporting is on).
It's like the $_SESSION is not true?
<?php
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
?>
<html>
<head>
<title>wa</title>
<link rel="stylesheet" type="text/css" href="../assets/stylesheet.css">
</head>
<body>
<div class="container">
CMS
<br />
<ol>
<li>Add Article</li>
<li>Delete Article</li>
<li>Logout</li>
</ol>
</div>
</body>
</html>
<?php
} else {
if (isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
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();
} else{
$error = 'Incorrect details!';
}
}
}
?>
<html>
<head>
<title>Visuality dashboard</title>
<link rel="stylesheet" type="text/css" href="../assets/stylesheet.css">
</head>
<body>
<div class="container">
CMS
<br /><br />
<?php if (isset($error)) { ?>
<small style="color:#aa0000;"><?php echo $error; ?>
<br /><br />
<?php } ?>
<form action="index.php" method="post" autocomplete="off">
<input type="text" name="username" placeholder="något">
<input type="password" name="password" placeholder="något">
<input type="submit" value="Login" />
</div>
</body>
<footer>
</footer>
</html>
<?php
}
?>
You need to call session_start(); at the beginning of your PHP file. If you have multiple files then adding it once to your connection file will work for all of them.
Read more on Sessions in PHP here
At line 39 md5$_POST['password']); you missed "("
md5($_POST['password']);
Every php file which has $_SESSION variable needs to include session_start(); on the top of the page.
When page gets a white screen after loading, you should see php_error_log for possible syntax errors (could be missing ";").
Please, review your code.
Hope it helps you.

PHP blank page after the login

I'm building a CMS for a website. The problem is that after the login a blank page appears and it stays until I hit refresh. Then it loads to the correct menu page and everything else is working correctly except this little detail. Any tips to solve this? Thanks, my code is below:
<?php
session_start();
include_once('../includes/connection.php');
if(isset($_SESSION['logged_in'])) {
//display index
?>
<html>
<head>
<meta charset="UTF-8">
<title>AdminENG</title>
<link rel ="stylesheet" href="../assets/style.css"/>
</head>
<body>
<div class="container">
CMS - ENG
<ol>
<li>Add Article</li>
<li>Delete Article</li>
<li>Logout</li>
</ol>
</div>
</body>
</html>
<?php
}
else {
//display login
if(isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
if (empty($username) || 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) {
//user entered the correct details
$_SESSION['logged_in'] = true;
header('Location: index.php');
exit();
}
else {
//user entered false details
$error = "Incorrect details!";
}
}
}
?>
<html>
<head>
<title>AdminENG</title>
<meta charset="UTF-8">
<link rel ="stylesheet" href="../assets/style.css"/>
</head>
<body>
<div class="container">
CMS
<br><br>
<?php
if (isset($error)) { ?>
<small style="color:#aa0000"><?php echo $error; ?></small>
<?php } ?>
<br><br>
<form action="index.php" method="post">
<input type ="text" name="username" placeholder="Username"/>
<input type="password" name="password" placeholder="Password"/>
<input type="submit" value="Login"/>
</form>
</div>
</body>
</html>
<?php
}
?>
Your header() redirection is probably not working. Check error log to see what the problem is. There must be absolutely no characters sent to the browser before the header() redirection, else it will fail.
My guess would be that those few spaces before <? in your script (if they are not copy/paste error) could interfere with head() redirection.
Anyway, check your error.log and see what do you have there.
You can't use Header after you execute html to the browser.
Try replace this: header('Location: index.php');
With this:
<script>window.location="index.php";</script>

Why Does My PHP Login Script Not Work?

I making an Employee Management System and I have stuck at a point where the Super Admin needs to be logged in to check/alter the details of the employees.
The Super Admin is just a single person which will do everything. So I have manually inserted the details of the super admin into the database.
Here's the code and the page is called as superadmin.php:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Employee Management System</title>
<link href="../styles/style-index.css" rel="stylesheet" type="text/css" media="screen"/>
<link href="styles/style-superAdmin.css" rel="stylesheet" type="text/css" media="screen"/>
</head>
<body>
<?php include_once("../php_includes/pageTop-template.php") ?>
<div id="pageContentforSuperAdmin">
<div id="content">
<div id="form-superAdmin" align="center">
<h3>Please Login Super Admin</h3>
<form id="superAdminForm" method="post" action="superadmin.php">
<input type="email" name="email" required class="txtInput" placeholder="Email..." autocomplete="off"/>
<br />
<input type="password" name="password" required class="txtInput" placeholder="Password..."/>
<br />
<input type="submit" name="submit" value="Enter" id="submit" />
</form>
</div>
</div>
</div>
<?php include_once("../php_includes/pageBottom-template.php") ?>
</body>
</html>
<?php
include_once("../php_includes/db-connect.php");
if (isset($_POST["submit"])) {
$email = mysqli_real_escape_string($con, $_POST["email"]);
$password = mysqli_real_escape_string($con, $_POST["password"]);
$hash = password_hash($password, PASSWORD_DEFAULT);
//echo $password;
$hash_ver = password_verify($password, $hash);
$sql = "SELECT * FROM employee WHERE email='".$email."' AND password='".$hash."'";
$query = mysqli_query($con, $sql);
$rows = mysqli_fetch_array($query);
if ($rows["email"] == $email && $rows["password"] == $hash) {
header("Location: admin-index.php");
} else {
echo 'Incorrect Credentials';
}
}
mysqli_close($con);
?>
Now the Problem is that, I am just getting the output as Incorrect Credentials and I don't know the reason why is it so ? For the password, I have used the newly introduced password_hash for hashing it. I have copied and pasted the hash code directly in the database table.
Any help would be appreciated.
Aside from anything else, I'd suggest you try by replacing your if with this:
if (mysqli_num_rows($query) > 0) {
header("Location: admin-index.php");
} else {
echo 'Incorrect Credentials';
}
As you're already selecting from the database where the username and password match.
if ($rows["email"] == $email && $rows["password"] == $hash) {
should be changed to check if there is a record found or not for $query.
like:
if(mysql_fetch_array($query) !== false) {

Categories