Search code examples
phpmysqlcrypt

Implement crypt() in php


I am trying to encrypt the given password to match one that is in a database. However using crypt() gives me a different result each time so it never matches. How can i make this work.

here is the statement that hashes the password given by the user.

if (empty($_POST) === false) {
        $username = $_POST['username'];
        $password = crypt($_POST['password']);

prior to this i manually made a user that had the crypt('password') but if I enter 'password' into the field it doesn not match.


Solution

  • Try below:

    if (isset($_POST['username']) && isset($_POST['password'])) {
      $username = $_POST['username'];
      $password = $_POST['password'];
    
      // get the hashed password from database
      $hashed_password = get_from_db($username);
    
      if (crypt($password, $hashed_password) == $hashed_password) {
        echo "Password verified!";
      }
    }