Jenson Jose
Jenson Jose

Reputation: 532

Unable to access cookie after page redirect

I am setting a cookie containing a vlue in this format and redirecting to another page via the PHP header function. Here's the code,

setcookie("myCookie", $cookieValue, time() + $cookieLife, "/"); // cookieLife is expiration time in sec
header("Location: $baseURL/index.php"); // $baseURL is "http://localhost/mysite"

The cookie is getting set within the browser. However, I am unable to access the cookie value in the redirected page, i.e., "index.php". I am trying to access the cookie value with a simple echo like this,

echo $_COOKIE['myCookie'];

However instead of the cookie value, I get the following notice,

Notice: Undefined index: myCookie in /path/to/my/site/index.php on line 1

I have set the cookie path to "/" after looking at other solutions but am still unable to solve this.

Any help much appreciated.

EDIT : I am testing this on XAMPP server, and the "mysite" here is actually an alias for another location on my hard drive. Could this be causing this issue?

Upvotes: 2

Views: 1665

Answers (1)

Parrotmaster
Parrotmaster

Reputation: 676

I assume your cookie gets removed or dissapears once you've left the previous page.

  1. Check if time() + $cookieLife is the desired time you want the cookie to live. The PHP setcookie function tells me that your $cookieLife is the time in seconds that you want your cookie to live, so make sure that it's the value you want it to be.

  2. Use an extension to check your current cookies (and alter them if you need to). This way you can check and make sure if the cookie is living as long as you want it to (you already mentioned seeing the cookie being set, but I will include this just in case + for future visitors).

FireFox Extension: Web Developer

Chrome Extension: Cookies

Upvotes: 1

Related Questions