duancong2160 2017-01-05 22:37
浏览 504
已采纳

将URL参数添加到Cookie

I am setting up an affiliate link area for my site and need to be able to store a URL query string into a cookie that expires in a 7 days.

Users will click on a link like: http://examplesite.com?afil=randomvalue.

I want to pull the key 'afil' and the value 'randomvalue' and put it in a cookie.

This will be used later down the road in another area of the site and I can't keep it in the URL.

I found this post: Set a Cookie based on url Parameter

But it doesn't seem to do what I want or set an expiration date. I am not sure if it is best to use php or javascript for this but I was planing on using php to pull the data later.

UPDATE:

I added this code to my dev site here: http://inventivewebdesign.com/dev/about?afil=great

<?php 
     $value=$_GET['afil']; //the value from the url
     setcookie("afilCookie", $value, strtotime( '+7 days' ));  /* expire in 7 days */
     echo "Cookie = " . $value;
?>

As you can see, it does display the cookie value (I added it right at the end of my header.php file which puts it in the body). For some reason it doesn't add it to my cookies when I view them.

Also, does this need to be made conditional for if there is no afil value?

  • 写回答

1条回答 默认 最新

  • du1843 2017-01-05 22:41
    关注

    http://php.net/manual/en/function.setcookie.php

    $value=$_GET['afil']; //the value from the url
    
    setcookie("TestCookie", $value, strtotime( '+7 days' ));  /* expire in 7 dasy */
    

    regarding its location with in the code flow the manual says:

    setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including and tags as well as any whitespace.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 echarts动画效果失效的问题。官网下载的例子。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加