简体   繁体   中英

Add password hash in pdo login

I cannot manage to add a password hash in my sign up code. I am new to PDO and I tried different things but cannot manage to make a working registration with password hash? Can someone help me: Here my code:

<?php
  include('header.php');  
  // Check if logged in
if($user->is_loggedin()!="")
{
    $user->redirect('home.php');
}
$error='';
if(isset($_POST['btn-signup']))
{


// trim empty spaces on inserted data
   $uname = trim($_POST['name']);
   $umail = trim($_POST['email']);
   $upass = trim($_POST['password']); 
   $repeat_password = trim($_POST['repeat_password']); 
   
//  validate username
   if($uname=="") {
      $error.= "provide username ! <br>"; 
   }
//  validate e-mail
   else if($umail=="") {
      $error.= "provide email id ! <br>"; 
   }
   else if(!filter_var($umail, FILTER_VALIDATE_EMAIL)) {
      $error.= 'Please enter a valid email address ! <br>';
   }
//  validate password
   else if($upass=="") {
      $error.= "provide password ! <br>";
   }
   else if(strlen($upass) < 6){
      $error.= "Password must be atleast 6 characters <br>"; 
   }
      else if( $upass!=$repeat_password){
      $error.= "Password Does Not Match <br>"; 
   }
   else
   {
    
    // check if email is already taken 
      try
      {
        //   prepare statement
         $stmt = $DB_con->prepare("SELECT email FROM users WHERE  email=:umail");
         $stmt->execute(array(':umail'=>$umail));
         $row=$stmt->fetch(PDO::FETCH_ASSOC);
    
         if($row['email']==$umail) {
            $error.= "sorry email id already taken ! <br>";
         }
        //  if everything is validated save data
         else
         {
            if($user->register($uname,$umail,$upass)) 
            {
                
                $_SESSION['success']='You have been Registered  Successfully';
                $user->redirect('login.php');
            }
         }
     }
    //  set the error mode
     catch(PDOException $e)
     {
        echo $e->getMessage();
     }
  } 
}

And here the class "user"

<?php
class User
{
    private $db;
 
    function __construct($DB_con)
    {
      $this->db = $DB_con;
    }
//  get user by passed in data
    public function register($uname,$umail,$upass)
    {
       try
       {
         //   $new_password = password_hash($upass, PASSWORD_DEFAULT); // Creates a password hash;
         $new_password = $upass;


           //    prepared statement
           $stmt = $this->db->prepare("INSERT INTO users(name,email,password,user_type) 
                                                       VALUES(:uname, :umail, :upass,'user')");
            // bind param with values
           $stmt->bindparam(":uname", $uname);
           $stmt->bindparam(":umail", $umail);
           $stmt->bindparam(":upass", $new_password);            
           $stmt->execute(); 
   
           return $stmt; 
       }
       //  set the error mode
       catch(PDOException $e)
       {
           echo $e->getMessage();
       }    
    }
 
    public function login($umail,$upass)
    {
       try
       {
        //  prepare statement
          $stmt = $this->db->prepare("SELECT * FROM users WHERE email=:umail  LIMIT 1");
          $stmt->execute(array(':umail'=>$umail));
          $userRow=$stmt->fetch(PDO::FETCH_ASSOC);
          if($stmt->rowCount() > 0)
          {
             if($upass==$userRow['password'])
             {
                $_SESSION['user_id'] = $userRow['id'];
                $_SESSION['name'] = $userRow['name'];
                   $_SESSION['role'] = $userRow['user_type'];
                return true;
             }
             else
             {
                return false;
             }
          }
       }
       //  set the error mode
       catch(PDOException $e)
       {
           echo $e->getMessage();
       }
   }
 
   public function is_loggedin()
   {
      if(isset($_SESSION['user_id']))
      {
         return true;
      }
   }
 
   public function redirect($url)
   {
       header("Location: $url");
   }
 
   public function logout()
   {
        session_destroy();
        unset($_SESSION['user_id']);
        return true;
   }
}
?>

In the commented line in the class script you can see a try I made, it hashed the password but then the pw wouldn't be saved in my sql database.

Sorry if the question is stupid but I am learning:)

I want to point out few things first:

  1. Do not use trim to users password. Unless if you want to restrict your users from entering spaces to their passwords.

  2. Use === when doing comparison. It is better because it checks datatype at the same time. For example if you have "2" and 2 and you use == operator it equals. It is good practice to check datatype because it prevents alot error from happening.

As what comes to problem that you wanted to get answer

You don't use password_hash function at any point. You only assign raw password to variable and assign this variable to bind_param function.

$new_password = $upass;

Should be instead

$new_password = password_hash($upass, PASSWORD_DEFAULT);

However i do not recommend using PASSWORD_DEFAULT as you could get more secure hash by using PASSWORD_ARGON2I. You can check more information about password_hash from PHP manual .

And to help you out even more: when you want to verify that user enters correct password at login you need to use password_verify(). It compares hash to password that user entered and if it is correct this function will return true.

Example:

$login_status = password_verify($_POST['password'], $user_password_from_database);
if($login_status === true) {//set session etc...}

You can read more about password_verify here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM