douyinbo3361 2014-07-25 00:07
浏览 23
已采纳

Cookie不适用于整个网站

I'm having two issues with setting and retrieving cookies.

  1. Cookie gets loaded but can't be called until page is refreshed. Meaning that the cookie shows up in developer tools but not when trying to use its value on the page. The value does seem available to use on page after refreshing.
  2. Cookie is not available across entire domain and subdirectories. For example, if the user enters at http://example.com/sub/ the goes to http://example.com/, the cookie gets destroyed.

Here's my code:

$ad_source = $_GET['source'];
$date_of_expiry = time() + (86400 * 7);
setcookie('ad_source',$ad_source,$date_of_expiry,'/');

if ( $_COOKIE['ad_source'] == 'adwords_campaign_01' ) {
    echo '... do something';
} elseif ( $_COOKIE['ad_source'] == 'adwords_campaign_02' ) {
    echo '... do something else';
}

I'm trying to to show different information throughout entire site by determining what adwords campaign the user clicked in on.

I don't usually use cookies and prefer to set a session, but in this case I want be able to track the source for a longer amount of time.

  • 写回答

1条回答 默认 最新

  • dongtao4890 2014-07-25 18:08
    关注

    Everything is working as expected now. A little more insightful information into cookies at this post helped a lot.

    PHP cookie set in second refresh page

    1. Redirect user to page after cookie is set. Second request from browser sends cookie, server returns info relative to its value.

    2. Check to see if $ad_source is set before creating cookie.

    The updated code:

    $ad_source = $_GET['source'];
    $date_of_expiry = time() + (86400 * 7);
    
    if ( $ad_source ) {
    
      setcookie('ad_source',$ad_source,$date_of_expiry,'/','example.com');
    
      if ( $_COOKIE['ad_source'] == 'adwords_campaign_01' ) {
        header( 'Location: http://example.com/' );
        echo '... do something';
      } elseif ( $_COOKIE['ad_source'] == 'adwords_campaign_02' ) {
        header( 'Location: http://example.com/' );
        echo '... do something else';
      }
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题