-6

i have a the following logon script on my website which works well:

<?php

include 'pdo_connect.php';
if(!empty($_POST)) {
    $query = "SELECT `password` FROM `users` WHERE `uname` = ?";
    $params = array($_POST['uname']);
    $results = dataQuery($query, $params);
}
$hash = $results[0]['password']; // first and only row if username exists;



if (password_verify($_POST['upassword'], $hash)) 
{
 session_start();
 $_SESSION["loggedIn"] = true;
    $_SESSION["username"] = ($_POST['uname']);
 echo "<script>window.location.replace('main.php')</script>";
} 
else 
{
  echo 'Invalid username/password, are you registered?';
}

?>

If a user enters an incorrect password for the username it returns a simple message but if you enter a wrong username it returns this:

error

  • 4
    Possible duplicate of [PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"](https://stackoverflow.com/questions/4261133/php-notice-undefined-variable-notice-undefined-index-and-notice-undef) – iainn Sep 06 '17 at 14:54
  • That is a notice not an error. – tousif Sep 06 '17 at 14:54

1 Answers1

1

Check if the array is not empty and index is set

<?php

include 'pdo_connect.php';
if(!empty($_POST)) {
$query = "SELECT `password` FROM `users` WHERE `uname` = ?";
$params = array($_POST['uname']);
$results = dataQuery($query, $params);
}
// check if array is not empty
if(is_array($results) && isset($results[0]['password']))
{
$hash = $results[0]['password']; // first and only row if username exist;
}   

if (isset($hash) && password_verify($_POST['upassword'], $hash))
{
session_start();
$_SESSION["loggedIn"] = true;
$_SESSION["username"] = ($_POST['uname']);
echo "<script>window.location.replace('main.php')</script>";
}
else
{
echo 'Invalid username/password, are you registered?';
}
?>
Bilal Akbar
  • 4,659
  • 1
  • 18
  • 29