0

I keep getting undefined index with the following code. I have a home.php page where the user can interact with the db and this is my verification code to check if the user is logged in or not.

<?php
  session_start();
  if ( isset($_SESSION['loggedin'])) {
    // logged in
  } else {
    header('Location: login.html');
  }
?>
<html>...
<span>
    <?php echo 'Welcome ' . ($_SESSION['name']) ; ?></span>
...
</html>

When checking the error_log file it says the warning comes from the line <?php echo 'Welcome ' . ($_SESSION['name']) ; ?>. I was expecting the php if statement to run before the html so it wouldn't reach the <?php echo 'Welcome ' . ($_SESSION['name']) ; ?> because it would redirect the user if he is not logged in.

Here is my authenticate.php

<?php
session_start();
$DB_HOST = 'localhost';
$DB_USER = 'blabla';
$DB_PASS = 'blabla';
$DB_NAME = 'blabla';
$con = mysqli_connect($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if ( mysqli_connect_errno() ) {
    die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
if ( !isset($_POST['username'], $_POST['password']) ) {
    die ('Username and/or password does not exist!');
}
if ($stmt = $con->prepare('SELECT id, password FROM admins WHERE username = ?')) {
    $stmt->bind_param('s', $_POST['username']);
    $stmt->execute(); 
    $stmt->store_result(); 
    if ($stmt->num_rows > 0) {
        $stmt->bind_result($id, $password);
        $stmt->fetch();      
        // Account exists, now we verify the password.
        if (password_verify($_POST['password'], $password)) {
            // loggedin
            $_SESSION['loggedin'] = TRUE;
            $_SESSION['name'] = $_POST['username'];
            $_SESSION['id'] = $id;
            header('Location: home');
        } else {
            header('Location: login.html?res=0'); 
        }
    } else {
        header('Location: login.html?res=0'); 
    }
    $stmt->close();
} else {
    echo 'Could not prepare statement!';
}
?>

Everything seems to work ok, I can log in, log out but I keep getting an error_log file that says PHP Notice: Undefined index: name in .../home.php

I confirm that the username gets posted correctly because when I log in, I can see the username value that comes from the db. It looks like it happens when I'm not logged in and I try to access home.php manually instead of going through login.html

Carlos27
  • 185
  • 9
  • 1
    A `header('Location: ...')` call doesn't stop execution, so the rest of your code will still execute. Always `exit` (or otherwise halt execution) after one. – ceejayoz Oct 01 '19 at 14:04
  • 1
    `header()` doesn't automatically redirect. Some output are buffered – Cid Oct 01 '19 at 14:04

0 Answers0