本文介绍下,一个功能强大的php cookie操作类,可以完成设置cookie、获取cookie值、删除cookie值等操作,有需要的朋友参考下。分享一个php cookie操作的类,可以设置cookie、获取cookie、删除cookie。
代码:
_name=$cname; if($cexpires){ $this->_expires=$cexpires; } else{ $this->_expires=time() + 60*60*24*30*12; // ~12 months } $this->_dir=$cdir; $this->_site=$csite; $this->_val=array(); $this->extract(); } function extract($cname=) { if(!isset($_cookie)){ global $_cookie; $_cookie=$globals[http_cookie_vars]; } if(empty($cname) && isset($this)){ $cname=$this->_name; } if(!empty($_cookie[$cname])){ if(get_magic_quotes_gpc()){ $_cookie[$cname]=stripslashes($_cookie[$cname]); } $arr=unserialize($_cookie[$cname]); if($arr!==false && is_array($arr)){ foreach($arr as $var => $val){ $_cookie[$var]=$val; if(isset($globals[php_self])){ $globals[$var]=$val; } } } if(isset($this)) $this->_val=$arr; } // 在全局范围内移除cookie unset($_cookie[$cname]); unset($globals[$cname]); } function put($var, $value) { $_cookie[$var]=$value; $this->_val[$var]=$value; if(isset($globals[php_self])){ $globals[$var]=$value; } if(empty($value)){ unset($this->_val[$var]); } } function clear() { $this->_val=array(); } function set() { if(empty($this->_val)){ $cookie_val=; } else { $cookie_val=serialize($this->_val); } if(strlen($cookie_val)>4*1024){ trigger_error(the cookie $this->_name exceeds the specification for the maximum cookie size. some data may be lost, e_user_warning); } setcookie($this->_name, $cookie_val, $this->_expires, $this->_dir, $this->_site); } } ?>
调用示例:1,设置cookie
put(namefirst,jo);$php_cookie->put(namelast,foo);$php_cookie->put(number,1234);$php_cookie->put(time,time()); // set the cookie$php_cookie->set();$php_cookie=new php_cookie(test_cookie 123);// add the variables to be saved in the cookie$php_cookie->put(namefirst,jo123);$php_cookie->put(namelast,foo13);$php_cookie->put(number,123413); // set the cookie$php_cookie->set();echo
the values saved in the cookie test_cookie are:;echo
namefirst: = $_cookie[namefirst];echo
namelast: = $_cookie[namelast];echo
number: = $_cookie[number];echo
time: = $_cookie[time];echo
end;?>
2,获取cookie
3,删除cookie
set();// clear all values#$php_cookie->clear();?>