建立商业站点或者功能比较完善的个人站点,常常需要记录访问者的信息,在PHP中提供了两种方便的手段:session和cookie功能.为了永久的保持用户信息,则cookie是最
一: 设置cookie
使用cookie前必须设置cookie.
函数原型:int setcookie(string name,string value,int expire,string path,string domain,int secure)
其中,除name外,所有的参数都是可选的,可以用空的字符串表示未设置.
属性value: 用来指定值.
属性path: 用来指定cookie被发送到服务器的哪一个目录路径下.
属性domain:能够在浏览器端对cookie的发送进行限定.
expire参数:用来指定cookie的有效时间,它是一个标准的Unix时间标记.
可以用time()或者mktime()函数取得,以秒为单位.
secure参数:表示这个cookie是否通过加密的HTTPS协议在网络上传输.
二: 设置cookie时的注意事项
在同一个页面中设置cookie,实际上是按从后往前的顺序进行的.如果要先删除一个cookie,再写入一个cookie,则必须先写写入语句,再写删除语句.否则会出现错误.
三: setcookie举例
简单的: setcookie("mycookie","value_of_mycookie");
带失效时间的: setcookie("withExpire","Expire_in_1_hour",time()+3600);
什么都有的:setcookie("FullCookie","Full_cookie_value",time+3600,"/forum","www.123.com",1);
四: cookie的一些特点
cookie是面向路径的.缺省path属性时,WEB服务器页会自动传递当前路径给浏览器.指定路径会强制服务器使用设置的路径.
在一个目录页面里设的cookie在另一个目录的页面里是看不到的.
五: 接收和处理cookie
PHP对cookie的处理是全自动的,和处理FORM变量的原则一样.当然也可以使用PHP全局变量,$HTTP_COOKIE_VARS数组.
例: echo $mycookie;
echo $cookie Array[0];
echo count($cookie Array);
echo $HTTP_COOKIE_VARS["mycookie"];
六: 删除cookie
(1)调用只带有name参数的setcookie();
(2)使失效时间为time()或time-1;
七: 使用cookie的限制
(1) 必须在HTML文件的内容输出之前设置;
(2)不同的浏览器对cookie的处理不一致,使用时一定要考虑;
(3)客户端的限制,比如用户设置禁止cookie,则cookie不能建立;
八: 一个具体的例子,希望大家对cookie有更加深刻的认识
复制代码 代码如下:
//cookie.php
if(!isset($flag))
{
setcookie("mycookie","this my cookie!");
header("location:cookie.php?flag=1");
exit;
}
?>
echo "cookie中有:".$mycookie;
?>
,美国空间,香港虚拟主机,虚拟主机

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Notepad++7.3.1
Easy-to-use and free code editor
