PHP-Cookie变量和会话变量的有趣行为 [英] PHP - funny behaviour of cookie variables and session variables

查看:64
本文介绍了PHP-Cookie变量和会话变量的有趣行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面写了一些PHP脚本来演示我的问题。像这样运行以下代码: http://localhost/test.php?test = 10 ,然后运行 http://localhost/test.php?test = 11 ,然后运行 http://localhost/test.php?test = 12 ,依此类推。您将看到该数字已回显到您的屏幕上的网址号始终是1位数字吗?

 

//如果查询字符串具有$ test,则存储在其中会话,并在稍后提供Cookie。
if($ _ GET [test]){
$ _SESSION [’test’] = $ _GET [test];
setcookie( test,$ _GET [test],time()+ 60 * 60 * 24 * 30 * 12 * 10); // 10年
}

//如果用户稍后返回,则从cookie
中获取$ test if(isset($ _ COOKIE [ test])){
$ _SESSION ['test'] = $ _COOKIE [ test];
}

回显会话测试:。 $ _SESSION ['test'];

后来,我用下面的代码解决了这个问题,但是解决起来还不够好,我想知道为什么会这样! / p>

此问题已解决:

 

if($ _ GET [cid ]){
setcookie( campaignid,$ _GET [cid],time()+ 60 * 60 * 24 * 30 * 12 * 10); // 10年
$ _SESSION ['campaignid'] = $ _GET [cid];
} elseif(isset($ _ COOKIE [ campaignid])){
$ _SESSION ['campaignid'] = $ _COOKIE [ campaignid];
}


解决方案


我无法获取cookie并立即读取相同的cookie?


是。您发送的Cookie仅在下一个请求中才能在$ _COOKIE数组中使用,因为$ _COOKIE超全局数组中填充了客户端请求中的数据。最初的请求什么都没有。


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"];
}

解决方案

Maybe because I cant a cookie and immediately read the same cookie?

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.

这篇关于PHP-Cookie变量和会话变量的有趣行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆