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 求差集那个函数有问题,有无佬可以解决
  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名