rivkamak
asked on
php cookies not working
In the head of my file, i set a cookie:
Then later on the page I have this if statement
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.
if (!isset($_COOKIE['curUrl']) || empty($_COOKIE['curUrl'] ) ) {
setcookie('curUrl','1' , time() + (86400 * 365), "/");
}
Then later on the page I have this if statement
<?php if ( isset($_COOKIE['curUrl']) && $_COOKIE['curUrl'] == "1" ) { ?>
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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:
because $_COOKIE is still empty. Instead, you need to explicitly initialize $_COOKIE not $varCookie:
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'];
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" ) { ?>
ASKER