0

Possible Duplicate:
PHP: “Notice: Undefined variable” and “Notice: Undefined index”

I just have a quick question about an error I received when I attempted to set and retrieve value of a cookie in PHP.

From this site and others, the following codes are the ones I am using to achieve this:

     <?php
     setcookie("edgeUser", $_POST['userName'], time()+0);
     echo $_COOKIE['edgeUser'];
     ?>

From what I understand, this will set a cookie with name="edgeUser", value="$userName" (which is provided from another page that is HTML), and will expire the moment that the user closes the session.

However, when I did run this, I got an error that apparently occurred on the "echo" line:

     Notice: Undefined index: edgeUser in C:\wamp\www\Login2.php on line **

Am I supposed to define "edgeUser" somewhere else in the code? I attempted to look into this, however, I either didn't see or didn't understand what else I am supposed to do. Any help would be greatly appreciated!

Community
  • 1
  • 1
PS Edge
  • 1
  • 1
  • 2

4 Answers4

4

You are setting the cookie to expire instantly:

setcookie("edgeUser", $_POST['userName'], time()+0);

Set it to

setcookie("edgeUser", $_POST['userName'], time()+($howLongItWillLast));

Edit: Sudhir also correctly points out it won't be available until the next page load. From the docs:

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.

Fluffeh
  • 33,228
  • 16
  • 67
  • 80
  • The op mentioned something about "until end of session". The PHP equivalent is to use an expiration of `0`. The browser will remove the cookie as soon as the session ends, which in most cases is when closing the browser. – Shi Aug 22 '12 at 23:56
2

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE and try setting cookie like

setcookie("edgeUser",  $_POST['userName'], time()+3600);  /* expire in 1 hour */
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
0

The problem (from the error), seems to be that either $_POST['userName'] or $_COOKIE['edgeUser'] (depending on what line the error is at) is undefined - that means it has not been set, and seeing that you actually set the cookie, my bet is that its the userName that is undefined. Make sure you are getting it, check with isset()

It could also be that the cookie expires before you get to echo it - in that case, use Fluffeh's solution.

Jeff
  • 12,085
  • 12
  • 82
  • 152
0

You set it and remove it in an instant. If you want to "remove as the user closes the session" you need to use $_SESSION['edgeUser'] = $_POST['userName'];

Soundz
  • 1,308
  • 10
  • 17