Robin Dieu
Robin Dieu

Reputation: 15

An index is Undefined inside a $_SESSION tag even tho I defined it right after I logged in

I am trying to display the users email after I logged in inside the header, but when I load the page it prompts me with an error saying the index "Email" is undefined evenb thought I defined in my login.php file.

Here are is the login.php file:

<?php


if (isset($_POST['email']) && isset($_POST['password']))
{   
    require_once 'connect.php';
    $email = $mysqli->escape_string($_POST['email']);
    $password = $mysqli->escape_string($_POST['password']);
    $result = $mysqli->query("SELECT * FROM users WHERE email='$email'");

    if ($result->num_rows == 0){
        echo "Did not find any user with this email.";
        exit();
    }
    else {
        $user = $result->fetch_assoc();
        if (password_verify($password, $user['Password'])){
            session_start();
            $_SESSION['ID'] = $user['ID'];
            $_SESSION['Email'] = $user['Email'];
            header("location: welcome.php");
        }
        else{
            echo "Wrong Password! Try again.";
            die();
    }
}
} 

?>

Here is my header.php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>WifiP | Home</title>
    <link rel="stylesheet" type="text/css" href="main.css">
    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
</head>
<body>
    <ul>
    <li><a href="index.php">Home</a></li>
    <li><a href="wifi_page.php">Wifi</a></li>
    <li><a href="login_page.php">Login</a></li>
    <li><a href="logout.php" class="logout">Logout</a></li>
    </ul>
    <?php
    session_start();
    echo $_SESSION['Email'];

    ?>

Here is my error:

enter image description here

Upvotes: 0

Views: 33

Answers (1)

Dimitrios Pantazis
Dimitrios Pantazis

Reputation: 454

The mistake is that session_start() should be before any html output. So just put it before DOCTYPE html and then do

$var = (empty($_SESSION['Email'])) ? '' : $_SESSION['Email'];
echo $var;

Also its a good practice after each header('Location:...") to die();

Upvotes: 1

Related Questions