PHP之学习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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version
Chinese version, very easy to use

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
