You also need to have session_start();
on top of the page where you check for that value, not only where you set it.
session_start();
if(!isset($_SESSION["name"])) {
header("Location: index.php");
die;
}
Question
I have a page called login.php. Login.php processes user information. If the passed user information is found in the database a new session is started. The name and password are then added to the super global sessions array
if(correct_password($name, $password, $users, $users_size)) {
session_start();
$_SESSION["name"] = $name;
$_SESSION["password"] = $password;
header("Location: account.php");
After the validation the user is redirected to account.php. I want to ensure that the user is logged in i.e the "name" index is set before they can access account.php. In order to do this I have the following code
if(!isset($_SESSION["name"])) {
header("Location: index.php");
die;
}
This code is suppose to check to see if the "name" index is set. If it is not set it means the user is not logged in and should therefore be directed back to index.php. However it seems that even if the user logs in the if always is true. I even tested
echo isset($_SESSION["name"]);
die;
to simplify things. When this is done nothing appears on the screen meaning that isset evaluated to false. If I try to print the global sessions array in account.php it works. The data prints and it shows that the name field is populated with the data submited from login.php.
What am I misunderstanding about isset? Or did I mess up somewhere else.
Thanks in advance.
Solution
You also need to have session_start();
on top of the page where you check for that value, not only where you set it.
session_start();
if(!isset($_SESSION["name"])) {
header("Location: index.php");
die;
}
OTHER TIPS
This can also work for you:
if( false == isset( $_SESSION ) && false == isset( $_SESSION['name'] )
header("Location: index.php");
die;
}
Storing username and password either in cookie and session is not a good idea try this will help you out
if (isset($_SESSION['name']) && null != $_SESSION['name']){
//name is exist don't forgot validate username against database
}
Hey to everyone who answered this question thank you. All your answers worked. The reason I thought they were not working is because I forgot to destroy the session after the user logged in. So even after log out the name index was still set.