Anyone see a way to improve this?

// inputs are form $_POST[] variables login and password

// relevant table columns are id,login,password,and sometimes key_chain
 // id is integer, the rest char with password being a hash 
 // the output success/fail flag is $id is set upon success, unset if failed

 //Check Keys Table for this Login
 if(isset($staff)) $sql = "SELECT `id`,`password`,`key_chain`"; else $sql = "SELECT `id`,`password`";
 $x = mysqli_real_escape_string($my_db_link,strtolower(trim($_POST['login'])));
 $sql .= " FROM `keys` WHERE `login`='$x';"; 
 $result = mysqli_query($my_db_link,$sql) or die(mysqli_error($my_db_link));
 unset($x);
 unset($id);

 // is there a matching login in the table?
 if (mysqli_num_rows($result)>=1) {
 
 //matching login found
 $row = mysqli_fetch_array($result);
 $id = $row['id'];
 $password = $row['password'];
 if(isset($staff)) $key_chain = $row['key_chain']; //text string to determine user's privilege
 mysqli_free_result($result);

 //if password is null, then it is not set yet, so set it
 if( (!isset($password)) OR (strlen(trim($password))<60) ){ //min hash length is 60

 // set the password
 $x = password_hash(mysqli_real_escape_string($my_db_link,strtolower(trim($_POST['password']))), PASSWORD_DEFAULT);
 $sql = "UPDATE `keys` SET `password`='$x' WHERE `id`='$id' LIMIT 1;";
 mysqli_query($my_db_link,$sql) or die(mysqli_error($my_db_link));
 unset($x);

 //if password not null, then test it
 } elseif (!password_verify( mysqli_real_escape_string($my_db_link,strtolower(trim($_POST['password']))),$password)) {
 // bad login -- wrong password
 unset($id);
 unset($key_chain);

 }//if(isset($id) AND

 }//if (mysqli_num_rows($result)>=1) {
 unset($password);
 unset($row);
 unset($sql);

Comments are closed