开发者

PHP Cookie won't parse

I'm trying to send the value of a cookie through a function, but it doesn't seem to be parsing. Here is a snippet of code I'm using:

function displayForm(){
   setcookie("site_Referral", $_GET['rid'], time()+10000);
   $ref_cookie = $_COOKIE['site_Referral'];
   $joinProc = new joinProcessor();
   return $joinProc->process($ref_cookie);
}

When I check my database there's no value being put through at all. If I change it to:

function displayForm(){
   setcookie("site_Referral", $_GET['rid'], time()+10000);
   $ref_cookie = 'foo';
   $joinProc = new joinPr开发者_JS百科ocessor();
   return $joinProc->process($ref_cookie);
}

The value 'foo' is entered just fine. I've also tried checking to see whether the cookie is set properly and it is - it appears on the Web Developer toolbar and when I write return $ref_cookie, it displays the correct value. It also doesn't work if I just use the $_GET value. What am I doing wrong?


The issue is that setcookie actually doesn't set anything. It should be called "sendcookie" as it is only concerned with crafting the Set-Cookie HTTP header. It does not store the value into the $_COOKIE array (which is only set when PHP first parses the current request.)

setcookie("abc", "xyz");    // Sends cookie header
print $_COOKIE["abc"];      // Read  existing cookie of CURRENT request

The $_COOKIE array will be updated on the next request, after you have setcookied it.

Use the temporary veriable directly in your code snippet:

function displayForm(){
   setcookie("site_Referral", $ref_cookie = $_GET['rid'], time()+10000);
   ...


As php.net states, setcookie() defines a cookie to be sent along with other HTTP headers. This means that it does not immediately set a cookie in _COOKIE. You can access it on the next page load assuming that no other headers (including any whitespace) have been output before calling setcookie().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜