I have admin page that will insert user id, password, role. The password will be hash after admin insert new user. It work well but when I try to login using the hash password, it will pop up "invalid user or password". Maybe because I put the password_verify coding in the wrong place. Can someone help me!!
Below is my coding
login.php
<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysqli_connect("localhost", "root", "","company");
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($connection, $username);
$password = mysqli_real_escape_string($connection, $password);
// SQL query to fetch information of registerd users and finds user match.
$query = mysqli_query($connection, "select * from login where password='$password' AND username='$username'");
$row=mysqli_fetch_assoc($query);
$rows = mysqli_num_rows($query);
if ($rows == 1) {
$pwdCheck = password_verify($password,$row['password']); $_SESSION['user']=array(
'username'=>$row['username'],
'password'=>$row['password'],
'role'=>$row['role']
);
$role=$_SESSION['user']['role'];
//Redirecting User Based on Role
switch($role){
case 'user':
if ($pwdCheck == true)
header("location: index.php"); // Redirecting To Other Page
break;
case 'admin':
if ($pwdCheck == true)
header("location: adminindex.php"); // Redirecting To Other Page
break;
}
}
else {
$error = "Username or Password is invalid";
}
mysqli_close($connection); // Closing Connection
}
}
?>
crud_include.php (admin insert new user)
if (isset($_POST['save'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$role = $_POST['role'];
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_query($db, "INSERT INTO login (username, password,role) VALUES ('$username', '$hashedPwd','$role')");
$_SESSION['message'] = "Successfully saved!";
header('location: crud.php');
}
the database (the hash work well but i cannot login using this user
Change your select query : In a where case use only username
<?php
$username=$_POST['username'];
$password=$_POST['password'];
$query = mysqli_query($connection, "select * from login WHERE username='$username'");
$row=mysqli_fetch_assoc($query);
$rows = mysqli_num_rows($query);
if ($rows == 1) {
if (password_verify($password, $row['password'])) {
echo 'Password is valid!';
if($role=$_SESSION['user']['role'] == 'user'){
header("location: index.php");
}elseif($role=$_SESSION['user']['role'] == 'admin'){
header("location: adminindex.php");
}
} else {
$error = "Password is invalid";
}
}else{
$error = "Username is invalid";
}
?>
Hope it will help you.
Here the the link for the hash password verified
Related
I am making a login and registration form and I use password_hash for password encryption, the problem is that when I log in it does not recognize my password and I get the error "the password is incorrect" (a message that I set). In the registration form there are no problems, but maybe it has to do with the error that I have.
Login.php
<?php
include 'connect/config.php';
session_start();
error_reporting(0);
if (isset($_SESSION["user_id"])) {
header('Location: home');
}
if (isset($_POST["signin"])) {
$email = mysqli_real_escape_string($conn, $_POST["email"]);
$password = mysqli_real_escape_string($conn, $_POST["password"]);
$check_email = mysqli_query($conn, "SELECT id FROM users WHERE email='$email' AND password='$password'");
if (mysqli_num_rows($check_email) > 0) {
$row = mysqli_fetch_array($check_email);
$_SESSION["user_id"] = $row['id'];
if (password_verify($password, $row['password'])){
$msg[] = "You have successfully logged in.";
}
header('Location: home');
} else {
$msg[] = "The password or email is incorrect.";
}
}
?>
Now, if I change the $check_email = mysqli_query($conn, "SELECT id FROM users WHERE email='$email' AND password='$password'"); to $check_email = mysqli_query($conn, "SELECT id, password FROM users WHERE email='$email'"); I can enter the home, but with any password and not the one I registered with.
Registration.php
<?php
include 'connect/config.php';
session_start();
error_reporting(0);
if (isset($_SESSION["user_id"])) {
header("Location: home");
}
if (isset($_POST["signup"])) {
$full_name = mysqli_real_escape_string($conn, $_POST["signup_full_name"]);
$email = mysqli_real_escape_string($conn, $_POST["signup_email"]);
$password = mysqli_real_escape_string($conn, $_POST["signup_password"]);
$cpassword = mysqli_real_escape_string($conn, $_POST["signup_cpassword"]);
$token = md5(rand());
$check_email = mysqli_num_rows(mysqli_query($conn, "SELECT email FROM users WHERE email='$email'"));
if ($password !== $cpassword) {
$msg[] = "Passwords do not match";
} elseif ($check_email > 0) {
$msg[] = "The email already exists, try another.";
} else {
$passHash = password_hash($password, PASSWORD_BCRYPT);
$sql = "INSERT INTO users (full_name, email, password, token, status) VALUES ('$full_name', '$email', '$passHash', '$token', '0')";
$result = mysqli_query($conn, $sql);
if ($result) {
header('Location: login');
$_POST["signup_full_name"] = "";
$_POST["signup_email"] = "";
$_POST["signup_password"] = "";
$_POST["signup_cpassword"] = "";
$msg[] = "Registered user successfully.";
} else {
$msg[] = "User registration failed, please try again later.";
}
}
}
?>
I hope you can help me.
Review my code but my low level of knowledge in php prevents me from finding the error, I hope you can do it for me, I will thank you
You should not have and password = '$password' in the query. The password in the database is the hashed password, not the same as $password. You should just fetch the row using the email, then use password_verify() to check the password.
You also need to select the password column so you can verify it.
$check_email = mysqli_query($conn, "SELECT id, password FROM users WHERE email='$email'");
You also have problems with your logic. You set the session variable and redirect to home regardless of the password verification. It should be:
$row = mysqli_fetch_array($check_email);
if ($row && password_verify($password, $row['password'])){
$msg[] = "You have successfully logged in.";
$_SESSION["user_id"] = $row['id'];
header('Location: home');
} else {
$msg[] = "The password or email is incorrect.";
}
You also shouldn't escape the password before hashing or verifying it. And of course, if you correctly use prepared statements with parameters, you shouldn't escape anything first.
I'm using password_verify with database when I login it always say password incorrect and in my database I'm using char 255 for password.
function login(){
global $db, $username, $errors;
// grap form values
$username = e($_POST['username']);
$password = e($_POST['password']);
$userrecord1 = mysqli_query($db, "SELECT * FROM users WHERE username='$_POST[username]' LIMIT 1");
if (count($userrecord1) == 1 ) {
$urow1 = mysqli_fetch_array($userrecord1);
$hash = $urow1["password"];
}
// attempt login if no errors on form
if (count($errors) == 0) {
$passuser = password_verify($password, $hash);
$query = "SELECT * FROM users WHERE (username='$username' OR email='$username') AND password='$passuser' LIMIT 1";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) { // user found
// check if user is admin or user
$logged_in_user = mysqli_fetch_assoc($results);
if ($logged_in_user['user_type'] == 'admin') {
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "Welcome admin";
header('location: /admin/home');
}else{
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "Welcome user";
header('location: /home/index');
}
}else {
array_push($errors, "Wrong username/password combination");
}
}
}
There's a few things I'd like to note,
Usage of the global keyword is not recommended - you should instead pass values as arguments to the function instead.
You are wide open to SQL injection - use a prepared statement
Once you have verified the password by password_verify(), the password is correct and the user has verified his login.
if (count($userrecord1) == 1 ) { doesn't make much sense, as you haven't fetched any records yet.
Your second select is moot (see point 3), and invalid as selecting from a hashed password will not yield the result.
Use exit; after header("Location: .."); calls
function login(){
global $db, $username, $errors;
// grap form values
$username = e($_POST['username']);
$password = e($_POST['password']);
$stmt = $db->prepare("SELECT password, user_type FROM users WHERE username=? LIMIT 1");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->bind_result($dbPassword, $userType);
if ($stmt->fetch() && password_verify($password, $dbPassword)) {
if ($userType == 'admin') {
$_SESSION['user'] = $username;
$_SESSION['success'] = "Welcome admin";
header('location: /admin/home');
exit;
} else {
$_SESSION['user'] = $username;
$_SESSION['success'] = "Welcome user";
header('location: /home/index');
exit;
}
} else {
$errors[] = "Wrong username/password combination";
}
}
My question is, when I try to log in with correct password, it still display the error message "You have entered wrong password, try again!".(Register works fine, the part checking if user already exist works fine) Here is the code:
register.php (works):
<?php
include('db_conn.php'); //db connection
session_start();
/* Registration process, inserts user info into the database
and sends account confirmation email message
*/
$_SESSION['email'] = $_POST['email'];
$_SESSION['full_name'] = $_POST['name'];
// Escape all $_POST variables to protect against SQL injections
$full_name = $mysqli->escape_string($_POST['name']);
$email = $mysqli->escape_string($_POST['email']);
$password = $mysqli->escape_string(password_hash($_POST['password'], PASSWORD_BCRYPT));
$usertype = $mysqli->escape_string("A");
$hash = $mysqli->escape_string( md5( rand(0,1000) ) );
// Check if user with that email already exists
$result = $mysqli->query("SELECT * FROM user WHERE Email='$email'") or die($mysqli->error());
if (isset($_POST["submit"])){
// We know user email exists if the rows returned are more than 0
if ( $result->num_rows > 0 ) {
$_SESSION['message'] = 'User with this email already exists!';
// header("location: error.php");
}
else { // Email doesn't already exist in a database, proceed...
$sql = "INSERT INTO user (Email, Password, UserType, FullName, Hash) "
. "VALUES ('$email','$password', '$usertype','$full_name', '$hash')";
// Add user to the database
if ( $mysqli->query($sql) ){
$_SESSION['logged_in'] = true; // So we know the user has logged in
$_SESSION['message'] =
"You are registered";
header("location: home.php");
}
else {
$_SESSION['message'] = 'Registration failed!';
// header("location: error.php");
}
}
}
?>
sign_in.php (not working properly):
<?php
include('db_conn.php'); //db connection
session_start();
$email = $mysqli->escape_string($_POST['email']);
$result = $mysqli->query("SELECT * FROM user WHERE Email='$email'");
if (isset($_POST["submit"])){
if ( $result->num_rows == 0 ){ // User doesn't exist
$_SESSION['message'] = "User with that email doesn't exist!";
// header("location: error.php");
}
else { // User exists
$user = $result->fetch_assoc();
echo $_POST['password'].$user['Password'];
if ( password_verify($_POST['password'], $user['Password']) ) {
$_SESSION['email'] = $user['Email'];
$_SESSION['full_name'] = $user['Name'];
$_SESSION['user_type'] = $user['UserType'];
// This is how we'll know the user is logged in
$_SESSION['logged_in'] = true;
header("location: home.php");
}
else {
$_SESSION['message'] = "You have entered wrong password, try again!";
// header("location: error.php");
}
}
}
?>
Don't escape the password hash, it is safe to input directly into the DB:
$mysqli->escape_string(password_hash($_POST['password'], PASSWORD_BCRYPT));
to:
password_hash($_POST['password'], PASSWORD_BCRYPT);
Im trying to create two different sessions. One for the admin, the other for normal users. If SQL returns admin_role as 1 = admin. If admin_role as 0 = user.
I have session_start() in the beginning of the document via include('connection.php'). When I press submit on my login form nothing really happens as for now.
if(empty($_POST["username"]) || empty($_POST["password"])){
$error = "Fill in both fields!";
} else {
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// To protect from MySQL injection
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($db, $username);
$password = mysqli_real_escape_string($db, $password);
// Check username and password from database
$sql = "SELECT admin_role FROM user WHERE user_name='$username' AND user_password='$password'";
$result = mysqli_query($db, $sql);
$admin_role = $row['admin_role'];
// If username and password exist in our database then create a session.
// Otherwise echo error.
if(mysqli_num_rows($result) == 1){
if($admin_role == 1){
$_SESSION['admin'];
header("location: logged-in.php");
}
if($admin_role == 0){
$_SESSION['username'];
header("location: logged-in.php");
}
} else {
$error = "Wrong credentials";
}
}
My problem with this code is that the IF statement which is deciding what page to go to seems to default to index.php. I have made a login table in MySQL already and have username/password column, and another column with a boolean value which states if the user is admin.
session_start(); // Starting Session
$error = ''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
} else {
// Define $username and $password
$username = $_POST['username'];
$password = $_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect(" ", " ", " ", " ");
// Selecting Database
$db = mysql_select_db(" ", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = "SELECT * FROM login WHERE username='$username' and password='$password'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
$count = mysql_num_rows($result);
$auth = $row['admin'];
if ($count == 1) {
if ($auth['admin'] == 1) {
session_start();
$_SESSION['admin'] = $auth;
$_SESSION['username'] = $username;
header("location: member.php");
} elseif ($auth['admin'] == 0) {
session_start();
$_SESSION['admin'] = $auth;
header("location:index.php");
}
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
Since you already extracted your admin value here:
$auth=$row['admin'];
You don't have to extract it here:
if($auth['admin']==1){
or here:
elseif($auth['admin']==0){
This simple change should fix your problem:
if($auth==1) {
...
} elseif($auth==0) {
...
In your original code, $auth['admin'] doesn't exist because $auth itself is just an integer, so it will pass the $auth['admin'] == 0 test since it is "falsy."
Also, it looks like you may have a case where $auth is completely undefined, in which case you should use "strict comparison" for that second condition, so you're looking for an actual zero and not just anything falsy:
} elseif($auth===0) {
I re wrote your login script. Try this. I think you'll find this will work much better for what your doing.
if(isset($_POST['username'])) {
$username = stripslashes($_POST['username']);
$username = strip_tags($username);
$username = mysql_real_escape_string($username);
$password = $_POST['password'];
//$password = md5($password);
$db_host = "host"; $db_username = "username"; $db_pass = "password"; $db_name = "db_name"; mysql_connect("$db_host","$db_username","$db_pass"); mysql_select_db("$db_name"); // connect to your database only if username is set
$sql = mysql_query("SELECT * FROM login WHERE username='$username' and password='$password'");
$login_check = mysql_num_rows($sql);
if($login_check > 0){ // if the user exists run while loop below
session_start(); // start session here (only once)
while($row = mysql_fetch_array($sql)){ // fetch the users admin from query
$auth = $row['admin'];
$_SESSION['admin'] = $auth; // set admin session variable
$_SESSION['username'] = $username; // set username session variable
if($auth == 1){
header("location: member.php"); // if user auth is 1, send to member
}else if($auth == 0){
header("location: index.php"); // if user auth is 0, send to index
}
exit();
}
} else {
header('Location: login.php'); // if user doesnt exist, reload login page.
}
mysql_close();
}
I recommend using md5 hash passwords.
When a person registers at your site, you can convert the password to md5 hash with this line $password = md5($password); prior to the db entry
Regarding your $auth above, this assumes your entry in the database is either a 0 or a 1. If you are controlling it this way, i recommend using enum in the sql database. set the type to "enum" and the type to '0', '1'
<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect(" ", " ", " ", " ");
// Selecting Database
$db = mysql_select_db(" ", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = "SELECT * FROM login WHERE username='$username' and password='$password'";
$result=mysql_query($query) or die(mysql_error());
$row= mysql_fetch_array($result);
$count=mysql_num_rows($result);
$auth= (int)$row['admin'];
if($count){
if($auth == 1){
$_SESSION['admin']= $auth;
$_SESSION['username']= $username;
header("location: member.php");
exit;
}elseif($auth == 0){
$_SESSION['admin']= $auth;
header("location:index.php");
exit;
}
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
?>
Try
header("Location: index.php");
exit;
header("Location: member.php");
exit;
Note the Capital L and the exit;
Also try if($auth == "1") and elseif($auth == "0") respectively.
If you value the security of your login page, use PDO or mysqli instead of mysql. It is deprecated and insecure due to its vulnerability to SQL injection.
Also, take advantage of PhP's password_hash and password_verifywhen handling storage and verification of passwords. It is a lot more secure compared to md5(). If you'd like examples of usage, let me know.