Link to home
Start Free TrialLog in
Avatar of rivkamak
rivkamakFlag for United States of America

asked on

php cookies not working

In the head of my file, i set a cookie:

	
 if (!isset($_COOKIE['curUrl']) || empty($_COOKIE['curUrl'] ) ) { 
setcookie('curUrl','1' , time() + (86400 * 365), "/");
 }

Open in new window


Then later on the page I have this if statement
<?php if ( isset($_COOKIE['curUrl'])  && $_COOKIE['curUrl'] == "1"  ) { ?>

Open in new window


For some reason, when the page loads, it's as if the cookie wasn't set yet.
Then if I reload the page, it recognizes the cookie.

What am I doing wrong that it's not picking it up right away.
ASKER CERTIFIED SOLUTION
Avatar of Leonidas Dosas
Leonidas Dosas
Flag of Greece image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of rivkamak

ASKER

Is there any other way to go about this besides using session?
Sessions have nothing directly to do with cookies.  It's not clear to me what problem you're having.  Have you read this page?  http://php.net/manual/en/function.setcookie.php
I should add a note.  Chrome will Not set a cookie on 'localhost'.  They feel that it is not a unique identity.  The rules of cookies are that the browser will return a cookie ONLY when the page requested matches the page that the cookie was set on.
>> So you can define and assign a variable to this cookie and use it something like this.
But like you correctly pointed out, "The cookie isn't set until the response is sent back to the client, and isn't available in your PHP until the next request from the client."

Thus, the following suggestion will not work:
$varCookie = $_COOKIE['curUrl'];

Open in new window


because $_COOKIE is still empty.  Instead, you need to explicitly initialize $_COOKIE not $varCookie:
if (!isset($_COOKIE['curUrl']) || empty($_COOKIE['curUrl'] ) ) { 
  setcookie('curUrl','1' , time() + (86400 * 365), "/");
  $_COOKIE['curUrl']='1';
 }

//code here
<?php if ( isset($varCookie)  && $varCookie == "1"  ) { ?>

Open in new window