2

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?

trejder
  • 17,148
  • 27
  • 124
  • 216
alecburger
  • 19
  • 1
  • 1
  • 4

3 Answers3

6

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";
}
trejder
  • 17,148
  • 27
  • 124
  • 216
Maz I
  • 3,664
  • 2
  • 23
  • 38
1

The issue is that the array $_SESSION doesn't have a key previouspage.

You can use the empty function to check that the key exists and that $_SESSION["previouspage"] has a value. Try using:

if(!empty($_SESSION["previouspage"])){
    //$_SESSION["previouspage"] exists!
}
Jim
  • 22,354
  • 6
  • 52
  • 80
  • thanks! I'll try. Finally someone that just explains it and not linking to other posts that don't make sense :)! – alecburger Jan 15 '14 at 12:09
  • @danronmoon This is not the case. See http://uk3.php.net/empty `That means empty() is essentially the concise equivalent to !isset($var) || $var == false` – Jim Jan 15 '14 at 12:10
  • @Jim you're right. A notice is only raised for an undeclared variable – danronmoon Jan 15 '14 at 12:15
0

Please try:

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";
}
Neeraj Kumar
  • 506
  • 1
  • 8
  • 19