-1

I am trying to learn password encryption in PHP but not quite getting it. So I am trying to use/implement sha1 encryption in my login form.

As you can see in this code, I used sha1 right next to my if/else condition and just getting an error.

<?php

$accountName = "accountuser";
$accountPass = "accountpass";

session_start();

if(isset($_SESSION['accountName'])) {
  echo "<h1>Welcome " .$_SESSION['accountName']."</h1>";

  header("Refresh: 3; url=index.php");
  include 'login.html';
  echo 'Logged in successfuly! <br> Logging in...';
}
  else {
    if($_POST['username']==$accountName && sha1$_POST['password']==$accountPass){

      $_SESSION['$accountName']=$accountName;

      header("Refresh: 3; url=index.php");

      echo 'Logged in successfuly! <br> Logging in...';
    }

    else {

      include 'login.html';

      echo "Wrong username!";

    }

  }

?>
curlpipesudobash
  • 691
  • 1
  • 10
  • 21

1 Answers1

1

Password hashing? There's a function for that.

While you can use functions like sha1(), md5() and others to encrypt passwords, it's not the best practise and generally not recommended.

You should use the built-in functions in PHP for this:

  • password_hash()
  • password_verify()

You need to use them like so:

$password = $_POST['password'];
$hash = password_hash($password, PASSWORD_DEFAULT);

Then store $hash in your database.


To verify whether a password is correct or not, use password_verify(), like so:

// $hash = stored hash in your database for the user
$password = $_POST['password']; // password put in by user attempting to login

password_verify($password, $hash);

password_verify() will either return TRUE or FALSE based on whether the password is correct or not. To check, you can just do this:

if(!password_verify($password, $hash)) { //password incorrect }

rpm192
  • 2,630
  • 3
  • 20
  • 38