Reputation:
I am making a website. Most of it is available to anybody visiting the site, but a small portion of it requires you to register to view. I have set up the login with Sessions. After someone logs in, it sets this:
$_SESSION['login'] = TRUE;
In one of the exclusive pages, at the top of the code before the content, I have written
if ($_SESSION['login'] == FALSE) {
header("loginpage.php");
}
However, if somebody is not logged in, that variable does not exist, and I end up with an error. Is there any other way to check if somebody is logged in? I would like something similar to what I already have, because I don't want to have to change everything.
Upvotes: 0
Views: 1432
Reputation: 26380
Do you have a script that always runs before each page executes? If not, this is a great place to set up any utility functions or initialize variables, like $_SESSION['login']
. You can set a default false value for $_SESSION['login']
there. Then you have a reliable default value, which is a good practice for a variable that's important, like this one.
You could use this to check if it's set and assign a default:
//Right after starting the session
if (!isset($_SESSION['login'])) {
$_SESSION['login'] = false;
}
If it's already got a value, this will be skipped.
You can also add an @
before a variable when you want to use it but you can't be sure it exists. This will suppress warnings about the existence of the variable, but I think it's better to know what the default value should be. Sometimes it's useful to get those warnings.
Upvotes: 0
Reputation: 10381
Simple solution : in the first page (or first script) of your website, create the session variable with value "false" :
<?php
session_start();
$_SESSION['login'] = FALSE;
?>
And, after some successfully logins you change the value to TRUE (as you are already doing) :
$_SESSION['login'] = TRUE;
This way the session variable will always exist, and you will not have problems with "unset" variables.
Upvotes: 0
Reputation: 3016
if(!@$_SESSION['login'])
{
header("location: logingpage.php");
exit();
}
Upvotes: 0
Reputation: 2704
You can use isset function to determine if a variable is set and is not null.
if (!isset($_SESSION['login']) || $_SESSION['login'] == FALSE) {
//user isn't logged in
header("loginpage.php");
}else{
//user is logged
}
Check the manual.
Upvotes: 1