dongxian7489 2015-09-15 14:54
浏览 206

如何在不重新加载页面的情况下获取最新的cookie ID?

There is a page, that can be visited with one of three params: ref1, ref2 and ref3. Each time page script sets a couple of cookies to store ref-param and time of it's creation. After that it should find the latest one and be ready to deal with it. For example if I have "ref1" cookie as latest before visiting page and visit

script.php?ref2=1 

it should echo

latest is ref2

But it works properly (echoes right latest cookie) only after additional reloading of the page. What's wrong with this code?

if ($_GET['ref1']) {
    setcookie('ref1', 'ref1');
    setcookie('ref1_dt', time());
}

if ($_GET['ref2']) {
    setcookie('ref2', 'ref2');
    setcookie('ref2_dt', time());
}

if ($_GET['ref3']) {
    setcookie('ref3', 'ref3');
    setcookie('ref3_dt', time());
}

function getLatestCookie() {
    $refs = array(
        'ref1' => $_COOKIE['ref1_dt'],
        'ref2' => $_COOKIE['ref2_dt'],
        'ref3' => $_COOKIE['ref3_dt']
    );
    $maxs = array_keys($refs, max($refs));
    return $maxs[0];
}

$latest = getLatestCookie();
setcookie('latest', $latest, time() + 60 * 60 * 24 * 30, "/");
echo "latest is " . $latest;
  • 写回答

1条回答 默认 最新

  • dsf45346 2015-09-16 07:35
    关注

    As usual, reading docs was good enough. Cookies are available in $_COOKIE array after next page loading. So in my case I should assign $latest to GET-param value if it exists and else assign it with getLatestCookie().

    评论

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能