php 处理cookie的类功能实例

内容摘要
这篇文章主要为大家详细介绍了php 处理cookie的类功能实例,具有一定的参考价值,可以用来参考一下。

对一个用于处理cookie的php类对此感兴趣的朋友,看看idc笔记做的技术笔记!
文章正文

这篇文章主要为大家详细介绍了php 处理cookie的类功能实例,具有一定的参考价值,可以用来参考一下。

对一个用于处理cookie的php类对此感兴趣的朋友,看看idc笔记做的技术笔记!

/**
 * 一个用于处理cookie的php类
 *
 * @param 
 * @arrange 五一二笔记网: 512Pic.com
 **/
 class cookieClass{
  var $cName = '';
  var $cTime = '';
  var $cSerialize = false;  
  var $cPath = '';
  function cookieClass($cookieName, $cookieTimeout, $cookieSerialize = false, $cookiePath = "/"){
   $this->cName = $cookieName;
   $this->cTime = $cookieTimeout;
   $this->cSerialize = $cookieSerialize;
   $this->cPath = $cookiePath;
   // This should fix the issue if you have cookies set and THEN turn on the serialization.
   $iname = $this->cName . "_S";
   if($this->cSerialize && !isset($_COOKIE[$iname])){
	$cookArr = array();
	foreach($_COOKIE as $name=>$val){
	 if(strpos($name,$this->cName) !== false ){ // make sure it is a cookie set by this application
	  $subname = substr($name,strlen($this->cName) + 1);
	  $cookArr[$subname] = $val;
	  $this->KillCookie($name);
	 }
	}
	$this->WriteCookie($cookArr);
   }
   // This is the opposite from above. changes a serialized cookie to multiple cookies without loss of data
   if(!$this->cSerialize && isset($_COOKIE[$iname])){
	$cookArr = unserialize($_COOKIE[$iname]);
	$this->KillCookie($iname);
	$this->WriteCookie($cookArr);
   }
  }
  function DestroyAllCookies(){
   foreach($_COOKIE as $name=>$val){
	if(strpos($name,$this->cName) !== false){
	 $_COOKIE[$name] = NULL;
	 $this->KillCookie($name);
	}
   }
  }
  function ReadCookie($item){
   if($this->cSerialize){
	$name = $this->cName . "_S";
	if(isset($_COOKIE[$name])){
	 // handle the cookie as a serialzied variable
	 $sCookie = unserialize($_COOKIE[$name]);
	 if(isset($sCookie[$item])){
	  return $sCookie[$item];
	 }else{
	  return NULL;
	 }
	}else{
	 return NULL;
	}
   }else{
	$name = $this->cName . "_" . $item;
	if(isset($_COOKIE[$name])){
	 // handle the item as separate cookies
	 return $_COOKIE[$name];
	}else{
	 return NULL;
	}
   } 
  }
  function KillCookie($cName){
   $tStamp = time() - 432000;
   setcookie($cName,"",$tStamp,$this->cPath);
  }
  function WriteCookie($itemArr){
   if($this->cSerialize){     
	$sItems = serialize($itemArr);
	$name = $this->cName . "_S";
	$_COOKIE[$name] = $sItems;
	$tStamp = time() + $this->cTime;
	setcookie($name,$sItems,$tStamp,$this->cPath);
   }else{
	$tStamp = time() + $this->cTime;
	foreach($itemArr as $nam=>$val){
	 $name = $this->cName . "_" . $nam;
	 $_COOKIE[$name] = $val;
	 setcookie($name,$val,$tStamp,$this->cPath);
	}e
   }
  }
 }
/***   来自php教程(www.idcnote.com)   ***/

注:关于php 处理cookie的类功能实例的内容就先介绍到这里,更多相关文章的可以留意

代码注释

作者:喵哥笔记

IDC笔记

学的不仅是技术,更是梦想!