首頁  >  文章  >  後端開發  >  php cookie類別(經典,值得收藏)

php cookie類別(經典,值得收藏)

WBOY
WBOY原創
2016-07-25 08:56:321009瀏覽
  1. /**

  2. --- 建立COOKIE 物件---
  3. $c = new cookie();
  4. --- 建立/更新COOKIE ---
  5. $c->setName(' myCookie ') // 必需
  6. ->setValue($value,true) // 必需- 第一個參數= 資料字串/數組,第二個參數= 加密(true=yes)
  7. ->setExpire( '+ 1 小時') // 可選- 預設為「0」或瀏覽器關閉
  8. ->setPath('/') // 可選- 預設為/
  9. ->setDomain('.domain. com') // 可選- 將嘗試自動偵測
  10. ->setSecure(false) // 可選- 預設false
  11. ->setHTTPOnly(false); // 可選- 預設false
  12. $c ->createCookie(); // 你也可以連結這個,必須是最後一個
  13. --- DESTROY COOKIE ---
  14. $c->setName('myCookie')->destroyCookie() ;
  15. $c->destroyCookie('myCookie');
  16. --- 取得COOKIE ---
  17. $cookie = $c->getCookie('myCookie',true ); // 第一個參數= cookie 名稱,第二個參數= 是否解密
  18. // 如果值為數組,則需要反序列化回傳
  19. ;*/

  20. Class Cookie {
  21. // cookie加密鍵值串,可以依自己的需要修改
  22. const DES_KEY = 'o89L7234kjW2Wad72SHw22lPZmEbP3dSj7TT10A5Sh60';
  23. 私有私有私有私有私有私有私什 = cookieData = null;

  24. 私有$cookieKey = null;
  25. 私有$cookieExpire = 0;
  26. 私有$cookiePath = '/';
  27. 私有$cookieDomain = null;
  28. 私有$se ;
  29. 私有$cookieHTTPOnly = false;
  30. /**
  31. * 建構子 設定域
  32. * @access public
  33. * @return none
  34. */
  35. public function __construct()
  36. {
  37. $this->cookieDomain = $ ();
  38. }
  39. /**
  40. * 取得cookie值
  41. * @access public
  42. * @param string $cookieName 要擷取的cookie
  43. * @param bool $decrypt 是否解密值
  44. */
  45. 公用函數getCookie($cookieName=null, $decrypt=false)
  46. {
  47. if(is_null($ cookieName)){
  48. $cookieName = $this->cookieName;
  49. }
  50. if( isset($_COOKIE[$cookieName])){
  51. return ($decrypt?Encryption( $_COOKIE[$cookieName],true):base64_decode($_COOKIE[$cookieName]));
  52. } else {
  53. $this->pushError($cookieName.'找不到');
  54. return false ;
  55. }
  56. }
  57. /**
  58. * 建立 cookie
  59. * @access public
  60. * @return bool true/false
  61. */
  62. public function createCookie()
  63. {
  64. if(is_null($this->cookieName)){
  65. $this->pushError('Cookie name was null');
  66. return false;
  67. }
  68. $ret = setcookie(
  69. $this->cookieName,
  70. $this->cookieData,
  71. $this->cookieExpire,
  72. $this->cookiePath,
  73. $this->cookieDomain,
  74. $this->cookieSecure,
  75. $this->cookieHTTPOnly
  76. );
  77. return $ret ;
  78. }
  79. /**
  80. * 清除cookie
  81. * @access public
  82. * @param string $cookieName 要殺死
  83. * @return bool true/false
  84. */
  85. public function destroyCookie($cookieName=null)
  86. {
  87. {
  88. if(is_null($cookieName)){
  89. $cookieName = $this->cookieName;
  90. }
  91. $ret = setcookie(
  92. $cookieName,
  93. null, null, null,
  94. (time()-1),
  95. $this->cookiePath,
  96. $this->cookieDomain
  97. );
  98. return $ret;
  99. }
  100. /**
  101. * 設定 cookie 名稱
  102. * @access public
  103. * @param string $name cookie 名稱
  104. * @return mix obj 或 bool false
  105. */
  106. public function setName($name=null)
  107. {
  108. if(!is_null($name)){
  109. $this->cookieName = $name ;
  110. return $this;
  111. }
  112. $this->pushError('Cookie 名稱為空');
  113. return false;
  114. }
  115. /**
  116. * 設定 cookie 值
  117. * @access public
  118. * @param string $value cookie 值
  119. * @return bool 字串是否為字串
  120. */
  121. public function setValue($value=null, $encrypt=false)
  122. {
  123. if(!is_null($value)){
  124. if(is_array($value)){
  125. $value = serialize($value);
  126. }
  127. $data = ($encrypt?$this->cookieEncryption($value):base64_encode($ value ));
  128. $len = (function_exists('mb_strlen')?mb_strlen($data):strlen($data));
  129. if($len>4096){
  130. $this->; PushError('Cookie 資料超過 4kb');
  131. return false;
  132. }
  133. $this->cookieData = $data;
  134. unset($data);
  135. return $this
  136. unset($data);
  137. return $this }
  138. $this->pushError('Cookie 值為空');
  139. return false;
  140. }
  141. /**
  142. * 設定cookie的過期時間
  143. * @access public
  144. * @param string $time +1 week, etc.
  145. * @return bool whether the string was a string
  146. */
  147. 公用函數setExpire( $time=0)
  148. {
  149. $pre = substr($time,0,1);
  150. if(in_array($pre, array('+','-'))){
  151. $this->cookieExpire = strtotime($time);
  152. return $this;
  153. } else {
  154. $this->cookieExpire = 0;
  155. return $this;
  156. }
  157. }
  158. /**
  159. * 設定cookie的儲存路徑
  160. * @access public
  161. * @param string $path
  162. * @return object $this
  163. */
  164. public function setPath($path='/')
  165. {
  166. $this->cookiePath = $path ;
  167. return $this;
  168. }
  169. /**
  170. * 設定cookie所屬的域
  171. * @access public
  172. * @param string $domain
  173. * @return object $this
  174. */
  175. public function setDomain($domain=null)
  176. {
  177. if(!is_null( $domain)){
  178. $this->cookieDomain = $domain;
  179. }
  180. return $this;
  181. }
  182. /**
  183. *
  184. * @access public
  185. * @param bool $secure true/false
  186. * @return object $this
  187. */
  188. public function setSecure($secure =false)
  189. {
  190. $this->cookieSecure = (bool)$secure;
  191. return $this;
  192. }
  193. /**
  194. * HTTPOnly 標誌,尚未被所有瀏覽器完全支援
  195. * @access public
  196. * @param bool $httponly yes/no
  197. * @return object $this
  198. */
  199. public function setHTTPOnly($httponly=false)
  200. {
  201. $this->cookieHTTPOnly = (bool)$httponly;
  202. return $this;
  203. }
  204. /***/
  205. 導管函數getRootDomain()
  206. {
  207. $host = $_SERVER['HTTP_HOST'];
  208. $parts =explode('.', $Host);
  209. if( count($parts)>1){
  210. $tld = array_pop($parts);
  211. $domain = array_pop($parts).'.'.$tld;
  212. } else {
  213. $網域= array_pop($parts);
  214. }
  215. return '.'.$domain;
  216. }
  217. /**
  218. * 如果未提供,則用於檢索根域的 Jenky 位元
  219. * @access private
  220. * @return string Le Domain
  221. */
  222. private function cookieEncryption($str =null, $decrypt=false)
  223. {
  224. if(is_null($str)){
  225. $this->pushError('無法加密/解密空字串');
  226. return $str ;
  227. }
  228. $iv_size = mcrypt_get_iv_size(MCRYPT_3DES, MCRYPT_MODE_ECB);

  229. $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
  230. $key_size = mcrypt_get_key_size(MCRYPT_3DES, MCRYPT_MODE_ECB);
  231. $key = substr(self::DES_KEY,0,$key_size);
  232. if($decrypt) > $return = mcrypt_decrypt(MCRYPT_3DES, $key, base64_decode($str), MCRYPT_MODE_ECB, $iv);

  233. } else {
  234. $return = base64_encode(mcrypt_encry, $ $iv));
  235. }
  236. return $return;

  237. }
  238. /**
  239. * 值加密
  240. * @access private
  241. * @param string $str 待加密的字串
  242. * @param string $decrypt 是否解密
  243. * @返回字串(解密|加密)加密字串
  244. */
  245. 初始化函數PushError($error =null)
  246. {
  247. if(!is_null($error)) {
  248. $this->errors[] = $error;
  249. }
  250. return;
  251. }
  252. /**
  253. * 將錯誤加到錯誤數組
  254. * @access public
  255. * @param string $error
  256. * @return none
  257. */
  258. public function getErrors( )
  259. {
  260. return implode("
    >", $this->errors);
  261. }
  262. }
複製程式碼

呼叫範例:

  1. require('cookie.class.php');

  2. // 樣本資料

  3. $array = array('foo'=>'bar','bar'=>'foo');
  4. $string = '這是一個字串';
  5. $c = new Cookie();

  6. /*

  7. 建立一個加密的cookie 資料庫
  8. */
  9. echo '

    加密陣列

    ';
  10. $start = microtime(true);

  11. $c->setName('Example') // 我們的cookie 名稱

  12. ->setValue($array,true) // 第二個參數,true,加密資料
  13. ->setExpire('+1 小時') // 1 小時後過期
  14. ->setPath(' /') // cookie 路徑
  15. ->setDomain('localhost') // 設定本地主機
  16. ->createCookie();
  17. $cookie = $c->getCookie('範例',true) ;
  18. $cookie = unserialize($cookie);
  19. $bench = sprintf('%.8f',(microtime(true)-$start));

    > ;
  20. echo print_r($cookie,true).'
    '.$bench.'秒


    ';
  21. /*

  22. 調查cookie
  23. */
  24. //$c->destroyCookie('Example');< ;/p>
  25. /*

  26. 建立一個cookie字串,直接瀏覽器關閉時故障
  27. */
  28. echo '

    常規未加密字串

    ' ;
  29. $start = microtime(true);
  30. $c->setName('Example1')
  31. - >setValue($string) // 第二個參數可以設定為false
  32. ->setExpire(0)
  33. ->gt ;setPath('/')
  34. ->setDomain('localhost')
  35. ->createCookie();
  36. $cookie = $c->getCookie ('範例1');

  37. $bench = sprintf('% .8f',(microtime(true)-$start));

  38. echo print_r($cookie,true).'
    '.$bench.'秒'; p>
複製程式碼


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn