Cookie的作用_PHP

WBOY
Release: 2016-06-01 12:40:56
Original
989 people have browsed it

Cookie

 1.记录访客的某些信息。例如可以利用Cookie纪录用户光临你的网页次数,
或者访客曾经输入过的信息,某些网站(如网易社区)可以自动纪录你上次登录
的用户名,用的就是Cookie。
  2.在页面之间传递变量。浏览器并不会保存当前页面上任何变量信息的,当
页面被关闭,页面上的任何变量信息将随之消失。如果你在一个页面有一个变量
a = 5,要把这个变量传递到另外一页,可以使用 http://url?a=5 方式传递变
量,或者在网页中插入一个表单,并在表单中插入一个隐含域(input hidden
field),以POST/GET方式传递到下一页。另外一种方式就是使用Cookie,把变
量以Cookie形式保存下来,然后在下一页通过读取该Cookie来获得变量的值。
注意:Cookie一定要在其他Header之前发送出去,否则出错!
下面一个纪录某访客来访次数的例子:

$HTTP_COOKIE_VARS["VisitTimes"]?($VisitTimes ++):($VisitTimes = 1);
setcookie("VisitTimes",$VisitTimes,time()+31536000);
echo "欢迎你第 ".$VisitTimes.
"
光临我的主页

\n";
?>
程序运行的结果如本页最顶所示(刷新一下看看访问的次数是否变化)。
PHP的Cookie函数为:
int setcookie(string name, string value, int expire, string path,
string domain, int secure);
string name
cookie 的名字
string value
cookie 的值
int exprie
cookie 的有效期,标准的 Unix timestamp
string path,domain
cookie 的路径和域名
int serure
cookie 是否以安全的http方式传送
  其中,除了参数 string name是必须的,其他参数均为可选。int expire 是
1970年1月1日00:00到某个时间的之间的秒差值。它的默认值为0,也就是说浏览
器关闭了cookie 将自动被删除。上面例子中有效期为一年(365*24*3600=31536000)。

再次重申:cookie 一定要在网页的其他header之前被发送,否则出错!!
Cookie 被设置之后,要读取其值,有两个方法:
直接把 cookie 的名字作为变量名字,即$name。
使用$HTTP_COOKIE_VARS["name"].
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!