PHP中的cookie是Web服务器存储在客户端计算机上的一个最大大小为4KB的小文件。它们通常用于跟踪信息,例如网站可以在用户下次访问网站时检索以个性化页面的用户名。Cookie只能从它所发布的域名中读取。Cookie通常设置在HTTP标头中,但JavaScript也可以直接在浏览器上设置cookie。
在PHP中设置Cookie:要在PHP中设置cookie,请使用setcookie()函数。setcookie()函数需要在脚本生成任何输出之前调用,否则cookie将无法设置。
语法:
setcookie(name,value,expire,path,domain,security);
参数:setcookie()函数通常需要六个参数,它们是:
以下是PHP中可以对Cookies执行的一些操作:
创建Cookies:创建一个名为Auction_Item的cookie,并将其值设置为Luxury Car。该cookie将在2天后过期(2天24小时60分钟*60秒)。
示例:此示例描述了在PHP中创建cookie的过程。
<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
echo "cookie is created."
?>
<p>
<strong>Note:</strong>
You might have to reload the
page to see the value of the cookie.
</p>
</body>
</html>
output:
检查是否设置了Cookie:在访问cookie的值之前,始终建议检查是否设置了cookie。因此,要检查是否设置了cookie,使用PHP的isset()函数。要检查是否设置了名为“Auction_Item”的cookie,isset()函数的执行方式如下:
示例:此示例描述了检查cookie是否设置的过程。
<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
if (isset($_COOKIE["Auction_Item"]))
{
echo "Auction Item is a " . $_COOKIE["Auction_Item"];
}
else
{
echo "No items for auction.";
}
?>
<p>
<strong>Note:</strong>
You might have to reload the page
to see the value of the cookie.
</p>
</body>
</html>
访问Cookie值:要访问Cookie值,请使用PHP的$_COOKIE超级全局变量。它是一个关联数组,包含当前请求中浏览器发送的所有Cookie值的记录。记录以列表的形式存储,其中Cookie名称用作键。要访问名为“Auction_Item”的Cookie,可以执行以下代码。
示例:此示例描述了访问和修改Cookie值的过程。
<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
echo "Auction Item is a " . $_COOKIE["Auction_Item"];
?>
<p>
<strong>Note:</strong>
You might have to reload the page
to see the value of the cookie.
</p>
</body>
</html>
删除Cookies:可以使用setcookie()函数删除cookie。要删除cookie,请通过传递cookie名称和其他参数或空字符串来调用setcookie()函数,但是这次需要将过期日期设置为过去。要删除名为“Auction_Item”的cookie,可以执行以下代码。
示例:此示例描述了删除cookie值的过程。
<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
setcookie("Auction_Item", "", time() - 60);
?>
<?php
echo "cookie is deleted"
?>
<p>
<strong>Note:</strong>
You might have to reload the page
to see the value of the cookie.
</p>
</body>
</html>
提示:
如果cookie的过期时间设置为0或省略,则cookie将在会话结束时到期,即当浏览器关闭时到期。
应该传递与创建cookie时使用的相同的路径、域名和其他参数,以确保删除正确的cookie。