I wrote a little PHP script below to demonstrate my question. Run the code below like this: http://localhost/test.php?test=10, then run http://localhost/test.php?test=11, then http://localhost/test.php?test=12, etc. You will see that the number echo’ed to your screen is always 1 digit behind the url number?! Maybe because I cant a cookie and immediately read the same cookie?
//If query string has $test, store in session, and cookie for later.
if($_GET[test]){
$_SESSION['test'] = $_GET[test];
setcookie("test", $_GET[test], time()+60*60*24*30*12*10); //10 years
}
//If user comes back later, then get $test from cookie
if (isset($_COOKIE["test"])){
$_SESSION['test'] = $_COOKIE["test"];
}
echo "session test: " . $_SESSION['test'];
Later, I solved the problem with the following code, but solving it is not good enough, I want to know WHY this happened!
This solved it:
if($_GET[cid]){
setcookie("campaignid", $_GET[cid], time()+60*60*24*30*12*10); //10 years
$_SESSION['campaignid'] = $_GET[cid];
}elseif (isset($_COOKIE["campaignid"])){
$_SESSION['campaignid'] = $_COOKIE["campaignid"];
}
Exactly. The cookie you sent is available in $_COOKIE array only in the next request, because the $_COOKIE superglobal array is filled with the data, that comes in the client’s request. And at first request it is nothing.