将URL参数添加到Cookie [英] Add URL Parameter to Cookie

查看:779
本文介绍了将URL参数添加到Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的网站设置会员链接区域,并且需要能够将URL查询字符串存储到7天后过期的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.

用户将点击以下链接: http:/ /examplesite.com?afil=randomvalue

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

我要提取键 afil和值 randomvalue并将其放在Cookie中。

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

稍后将在网站的其他区域使用它,我无法将其保留在URL中。

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

我发现了这篇文章:根据url参数设置Cookie

但是它似乎并没有满足我的要求或设置了失效日期。我不确定是否最好使用php或javascript,但是我打算以后使用php提取数据。

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.

更新:

我将此代码添加到了我的开发站点: http: //inventivewebdesign.com/dev/about?afil=great

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;
?>

如您所见,它确实显示了cookie值(我在末尾添加了它) header.php文件,将其放在正文中)。出于某些原因,当我查看它们时,它不会将其添加到我的cookie中。

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.

此外,如果没有afil值,是否需要将其设置为条件? / p>

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

推荐答案

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()定义要与其他
HTTP标头一起发送的cookie。像其他标头一样,必须在脚本的
输出之前发送cookie(这是协议限制)。此
要求您在任何输出,
包括和标记以及任何空白之前放置对该函数的调用。

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.

这篇关于将URL参数添加到Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆