Cookie

1.创建 Cookie

setcookie() 函数用于设置 cookie。[8] 
注释:setcookie() 函数必须位于 <html> 标签之前。
语法:
setcookie(name, value, expire, path, domain);
在下面的例子中,我们将创建名为 "user" 的 cookie,并为它赋值 "Alex Porter"。我们也规定了此 cookie 在一小时后过期:
 
<?php
setcookie("user","AlexPorter",time()+3600);
?>
 
<html>
.....
注释:在发送 cookie 时,cookie 的值会自动进行 URL 编码,在取回时进行自动解码。(为防止 URL 编码,请使用 setrawcookie() 取而代之。)

2.取回 Cookie 值

 


PHP 的 $_COOKIE 变量用于取回 cookie 的值。[8] 
  在下面的实例中,我们取回了名为 "user" 的 cookie 的值,并把它显示在了页面上:
 
<?php
//Printacookie
echo$_COOKIE["user"];
 
//Awaytoviewallcookies
print_r($_COOKIE);
?>
在下面的实例中,我们使用 isset() 函数来确认是否已设置了 cookie:
 
<html>
<body>
 
<?php
if(isset($_COOKIE["user"]))
echo"Welcome".$_COOKIE["user"]."!<br>";
else
echo"Welcomeguest!<br>";
?>
 
</body>
</html>

3.删除 Cookie

当删除 cookie 时,您应当使过期日期变更为过去的时间点。[8] 
删除的实例:
 
<?php
//settheexpirationdatetoonehourago
setcookie("user","",time()-3600);
?>
posted @ 2015-12-01 15:36  Sun丶老板  阅读(132)  评论(0编辑  收藏  举报