"Notice: Undefined index" when trying to read $_SESSION array
php, session
Solution
Use `isset()` function:
if(isset($_SESSION["previouspage"])) {
echo "<a href=".$_SESSION["previouspage"].">Go back.</a>";
$_SESSION["previouspage"] = "index.php";
}else {
//No go back button will be displayed.
$_SESSION["previouspage"] = "index.php";
}
Problem
I have an irritating problem and I can't seem to fix it, I watched some videos on YouTube and read through the php.net documentation about error but this `$_SESSION` error needs your help! The exact error, I get is this: ``` Notice: Undefined index: previouspage C:\Users\Administrator\Documents\Localhost\root\test\index.php on line 5 ``` What I have created is a goback button using a session variable. When the variable is already defined in my script there's no problem but when "the user" visits the website for the first time there is no "previous page" yet. The error above is what I then get. How can I fix this? I have this PHP code: ``` <?php session_start(); if($_SESSION["previouspage"]) { echo "<a href=".$_SESSION["previouspage"].">Go back.</a>"; $_SESSION["previouspage"] = "index.php"; }else { //No go back button will be displayed. $_SESSION["previouspage"] = "index.php"; } ``` ?> So, when there's no history yet I get the error, otherwise not. How to fix this?
Related problems
- "Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
- Reference - What does this error mean in PHP?
- "Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
- Reference - What does this error mean in PHP?