1.创建 Cookie
注释: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 //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
删除的实例:
<?php //settheexpirationdatetoonehourago setcookie( "user" , "" ,time()-3600); ?> |