0

I a have function that saves an information using a cookie. The problem is, when the webpage loads for the first time i got the error undefined variable "pagination_pos"...How will i set a temporary value of this cookie as blank first so that i can prevent this error..Here is the function:

    function getPaginationPos(){
if (isset($_REQUEST['page']) && !empty($_REQUEST['page'])){
setcookie('pagination_pos',$_REQUEST['page'],time() + 86400);
return $_REQUEST['page'];
} else {
return ($_COOKIE['pagination_pos']!='' ? $_COOKIE['pagination_pos'] : 1);
}

}

I get the undefined variable at line 6

Resnef Immatong
  • 55
  • 1
  • 12
  • Is there any code before this? Or are the line numbers correct here? – Ryan Smith Apr 25 '14 at 03:18
  • @RyanSmith it would have to be that line. The variable that throws the error is called "pagination_pos", which is only referenced on the 6th line shown here. – Liftoff Apr 25 '14 at 03:26
  • @David Undefined superglobals don't throw errors on my configuration. They only return NULL. – Ryan Smith Apr 25 '14 at 03:36

2 Answers2

0

If the Cookie is not set - you shouldn't "return" it - you should use this

     } else {
     return NULL;
     }
sarah
  • 102
  • 2
  • 10
0

This error shows up because you are attempting to test and return a variable that has not been initialized.

The recommended solution is to use isset(), rather than comparing it to an empty string:

return (isset($_COOKIE["pagination_pos"]) ? $_COOKIE["pagination_pos"] : 1);

You should also note that this error only appears because you have PHP setup to display E_NOTICE errors. You can disable that functionality if you wish, though it is "recommended during development."


This question has been dubbed the "General Reference Question" for this type of error. You can find some really detailed explanations there.

Community
  • 1
  • 1
Liftoff
  • 24,717
  • 13
  • 66
  • 119
  • Thanks @David...I should have thought about isset()...Im sorry im still learning more on web development...Now my pagination is working fine... – Resnef Immatong Apr 25 '14 at 04:02