PHP Cookie 统计访问次数实现
具体代码实现如下所示:
<?php
$_COOKIE["counter"]?($c=$_COOKIE["counter"]+1):($c=1);
setCookie("counter",$c,time()+60);
echo "欢迎您第".
<font color="#ff0000">".$c."</font>次访问cookie";
?>在该应用程序的运行流程中,首先由浏览器发起对资源(即该PHP页面)的请求,并向服务器发送如下的HTTP头部信息:
GET http://localhost/index.php HTTP/1.1
HOST:localhost
Accept:*/*
Accept-language:zh-cn
Accept-Encoding:gzip,deflate
User-Agent:Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)
Connection:Keep-Alive
---------------------------------------------------------------------------
随后,动态网页程序(index.php)负责创建Cookie,此时服务器会向浏览器返回如下的HTTP响应报头内容:
HTTP/1.1 200 OK
Server:Apache/2.2.6 (Win32) PHP/5.2.6
Date:Fri,23 Mar 2009 23:15:55 GMT
Connection:Keep-Alive
Content-Length:65
Content-Typt:text/html
Set-Cookie:VisitorCount=1; expires=Thr,30-Jul-2010 16:00:00 GMT;domain=localhost;path=/
Cache-control:private
GET http://localhost/index.php HTTP/1.1
---------------------------------------------------------------------------
上述操作将在客户端保存一个Cookie文件,并存储$c变量的值。
当用户再次发起请求时,浏览器会将已保存的Cookie数据发送给服务器,例如以下HTTP请求报头示例:
Accept:*/*
Accept-language:zh-cn
Pragma:no-cache
User-Agent:Mozilla/4.0(compatible;MSIE 6.0;Windows NT 5.1; SV1)
Host:localhost
Connection:Keep-Alive
Cookie:VisitorCount=1