duaiwu8385 2015-12-04 18:51
浏览 32

在第一页加载时设置cookie

I am trying to set a cookie in wordpress that comes from $_GET so I've put this in the bottom of my theme's functions.php:

function set_name_cookie() {
    if (isset($_GET['kw'])) {
        setcookie('kw',$_GET['kw'], time()+3600*24, '/','.website.com',false);   
    }
}
add_action( 'init', 'set_name_cookie');

I can see cookies as they're set in Firefox. This cookie is not set when I first load the page, but if I reload the page it is.

Many people have a similar issue where cookie is not set until after the page is loaded so they can't use $_COOKIE['kw'] dynamically in the same page as it's set, but that's not my issue, it's just not setting, when I go to the next page, the $_COOKIE is still empty unless I reload that first page (with the ?kw=XXX in the URL). What could cause that behavior? Is this how it's supposed to work?

EDIT - When I go to mysite.com/test.php?kw=123 which looks like this:

<?
session_start();
if (isset($_GET['kw'])) {
    setcookie('kw',$_GET['kw'], time()+3600*24,'/',$_SERVER['HTTP_HOST'],false);   
}
?>
<html>
    <a href="test2.php">check cookie</a>
</html>

And then click on the link to test2.php, which looks like this:

session_start();
echo 'cookie:'.print_r($_COOKIE);
exit;

I don't see a cookie it's just empty array. If I go back in my browser to test.php and then click through again, I can see it. Am I missing something really obvious?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 划分vlan后不通了
    • ¥15 GDI处理通道视频时总是带有白色锯齿
    • ¥20 用雷电模拟器安装百达屋apk一直闪退
    • ¥15 算能科技20240506咨询(拒绝大模型回答)
    • ¥15 自适应 AR 模型 参数估计Matlab程序
    • ¥100 角动量包络面如何用MATLAB绘制
    • ¥15 merge函数占用内存过大
    • ¥15 Revit2020下载问题
    • ¥15 使用EMD去噪处理RML2016数据集时候的原理
    • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大