php 设置cookie与清除cookie方法

setcookie()函数定义一个cookie被发送的http头的其余部分一起,像其他头,饼干之前,必须发送从你的脚本,这是一个协议限制输出,这就需要你的地方调用这个函数之前,任何输出,包括<html>和<head>标签以及任何空格.

一旦饼干已经确定,他们可以访问下一页上加载了$ _cookie或$ http_cookie_vars数组,请注意,如超全局变量$ _cookie形式适用于php的4.1.0,cookie的值也存在于$ _request数组,代码如下:

  1. bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
  2. function makecookie($var, $value, $life = 0, $prefix = 0) //设置cookie
  3. {
  4. global $cookiepre, $cookiedomain, $cookiepath, $timestamp, $_server;
  5. setcookie(($prefix ? $cookiepre : '').$var, $value,
  6. $life ? $timestamp + $life : 0, $cookiepath,
  7. $cookiedomain, $_server['server_port'] == 443 ? 1 : 0);
  8. }
  9. function clearcookies() //清除cookie
  10. {
  11. global $uid, $username, $pw, $adminid;
  12. makecookie('auth', '', -86400 * 365);
  13. $uid = $adminid = 0;
  14. $username = $pw = '';
  15. }
  16. //实例代码如下:
  17. makecookie('111','www.phpfensi.com');
  18. //清除cookie
  19. clearcookies();
  20. //下面兴一个支持二级域名cookie函数吧。
  21. function setcookielive($name, $value='', $expire=0, $path='', $domain='', $secure=false, $httponly=false) {
  22. //set a cookie as usual, but also add it to $_cookie so the current page load has access
  23. $_cookie[$name] = $value;
  24. return setcookie($name,$value,$expire,$path,$domain,$secure,$httponly);
  25. }
  26. //调用方法,代码如下:
  27. setcookielive('webab','111cn',time()+86000,'/','111cn.net');
  28. //一入门级cookie设置方法
  29. setcookie("cookie[three]", "cookiethree");
  30. setcookie("cookie[two]", "cookietwo");
  31. setcookie("cookie[one]", "cookieone");
  32. // after the page reloads, print them out
  33. if (isset($_cookie['cookie'])) {
  34. foreach ($_cookie['cookie'] as $name => $value) {
  35. echo "$name : $value <br /> ";
  36. }
  37. }