PHP changing the header dependant on whether a user is logged in


#1

Hi I’ve ran into a problem when trying to code a login system for a website I want to make. I have tried using a IF statement to determine whether the user is already logged in or not and to have to a different header appear depending on the outcome. When I run the website I get a 'notice undefined index: ‘Logged_in’ which is the variable used so that I know the user is logged in. Any help would be appreciated thanks.

[php]<?php
/* Displays user information and some useful messages */
session_start ();

// Check if user is logged in using the session variable
if ($_SESSION[‘logged_in’] != 1) {
include_once(“headernotloggedin.php”);
} else {

        // Makes it easier to read
        $first_name = $_SESSION['first_name'];
        $last_name = $_SESSION['last_name'];
        $email = $_SESSION['email'];
        $active = $_SESSION['active'];
        include_once ("headerloggedin.php");
    }
    ?> [/php]

//The script to determine whether the user is logged in//

[code]<?php
/* User login process, checks if user exists and password is correct */

// Escape email to protect against SQL injections
$email = $mysqli->escape_string($_POST[‘email’]);
$result = $mysqli->query(“SELECT * FROM users WHERE email=’$email’”);

if ( $result->num_rows == 0 ){ // User doesn’t exist
$_SESSION[‘message’] = “User with that email doesn’t exist!”;
header(“location: error.php”);
}
else { // User exists
$user = $result->fetch_assoc();

if ( password_verify($_POST['password'], $user['password']) ) {
    
    $_SESSION['email'] = $user['email'];
    $_SESSION['first_name'] = $user['first_name'];
    $_SESSION['last_name'] = $user['last_name'];
    $_SESSION['active'] = $user['active'];
    
    // This is how we'll know the user is logged in
    $_SESSION['logged_in'] = true;

    header("location: profile.php");
}
else {
    $_SESSION['message'] = "You have entered wrong password, try again!";
    header("location: error.php");
}

}
?>[/code]

//The login script


#2

If the user is not logged in $_SESSION[‘logged_in’] does not exist.

Just change
[php]if ($_SESSION[‘logged_in’] != 1) {[/php]

to
[php]if (isset($_SESSION[‘logged_in’])) {[/php]

Since the session key is not set if the user is not logged in just checking if it’s there effectively also checks if the user IS logged in. So I saw no need to do both isset and != 1


#3

Do not create variables for nothing and never ever put variables in your query. Use Prepared Statements. Do not SELECT *. Specify the columns you want.