怎么写&在相同的请求中打印一个PHP cookie? [英] How to write & print a PHP cookie in the same request?

查看:29
本文介绍了怎么写&在相同的请求中打印一个PHP cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定为什么,但是以下内容似乎无法正常工作:

I'm not sure why, but the following doesn't seem to work as expected:

<?php
    setcookie('my_cookie', $_GET['v'], time() + (86400 * 7)); 
    echo $_COOKIE['my_cookie'];
?>

如果将其放在PHP Web服务器上的文件中,并使用查询 yourdomain.com/index.php?v=value 进行调用.该值仅在第二个请求上打印到页面上.为什么不一日呢?

If you put this in a file on a PHP web server and call it with a query of yourdomain.com/index.php?v=value. The value only gets printed to the page on the 2nd request. Why not on the 1st?

推荐答案

$_COOKIE 数组仅表示来自客户端请求的那些cookie. setcookie()添加了HTTP标头,要求客户端在后续请求.

The $_COOKIE array represents only those cookies that came in the request from the client. setcookie() adds an HTTP header asking the client to send the cookie during subsequent requests.

通常,您不应该想要使它看起来像请求中包含的cookie比实际更多.相反,通常应该在脚本中 early 处理cookie,在其他地方维护状态,并在脚本中 late 设置或重置cookie.

Typically, you shouldn't want it to appear like more cookies were in the request than actually were. Rather, you should generally process cookies early in the script, maintain state elsewhere, and set or reset cookies late in the script.

这篇关于怎么写&amp;在相同的请求中打印一个PHP cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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