ホームページ  >  記事  >  バックエンド開発  >  php cookie クラス (クラシック、収集する価値あり)

php cookie クラス (クラシック、収集する価値あり)

WBOY
WBOYオリジナル
2016-07-25 08:56:321008ブラウズ
  1. /**

  2. --- クッキー オブジェクトの作成 ---
  3. $c = new cookie();
  4. --- クッキーの作成/更新 ---
  5. $c->setName('myCookie') // 必須
  6. -> setValue($value,true) // 必須 - 1 番目のパラメータ = データ文字列/配列、2 番目のパラメータ = encrypt (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. OR
  16. $c->destroyCookie( 'myCookie');
  17. --- COOKIE を取得 ---
  18. $cookie = $c->getCookie('myCookie',true); // 1 番目のパラメータ = Cookie 名、2 番目のパラメータ = 復号化するかどうか
  19. // 値が配列の場合、戻り値をアンシリアル化する必要があります

  20. */

  21. Class Cookie {
  22. // cookie加密键值串、必要に応じて変更可能
  23. const DES_KEY = bP3dSj7TT10A5Sh60';

  24. private $errors = array();

  25. private $cookieName = null;
  26. private $cookieData = null;
  27. private $cookieKey = null;
  28. private $cookieExpire = 0;
  29. private $cookiePath = '/';
  30. private $cookieDomain = null;
  31. private $cookieSecure = false;
  32. private $cookieHTTPOnly = false;
  33. /**
  34. * コンストラクターはドメインを設定します
  35. * @access public
  36. * @return none
  37. */
  38. public function __construct()
  39. {
  40. $this->cookieDomain = $this->getRootDomain() ;
  41. }
  42. /**
  43. * 获取cookie值
  44. * @access public
  45. * @param string $cookieName 取得するクッキー
  46. * @param bool $decrypt 値を復号化するかどうか
  47. */
  48. public function getCookie($cookieName=null, $decrypt=false)
  49. {
  50. if(is_null($cookieName)){
  51. $cookieName = $this->cookieName ;
  52. }
  53. if(isset($_COOKIE[$cookieName])){
  54. return ($decrypt?$this->cookieEncryption($_COOKIE[$cookieName],true):base64_decode($_COOKIE[$cookieName])) ;
  55. } else {
  56. $this->pushError($cookieName.' not found');
  57. return false;
  58. }
  59. }
  60. /**
  61. * Cookie を作成します
  62. * @access public
  63. * @return bool true/false
  64. */
  65. public function createCookie()
  66. {
  67. if (is_null($this->cookieName)){
  68. $this->pushError('Cookie 名が null でした');
  69. return false;
  70. }
  71. $ret = setcookie(
  72. $this->cookieName,
  73. $this->cookieData、
  74. $this->cookieExpire、
  75. $this->cookiePath、
  76. $this->cookieDomain、
  77. $this->cookieSecure、
  78. $this->cookieHTTPOnly
  79. );
  80. return $ret;
  81. }
  82. /**
  83. * 清除cookie
  84. * @access public
  85. * @param string $cookieName to kill
  86. * @return bool true/false
  87. */
  88. public function destroyCookie($cookieName=null)
  89. {
  90. if(is_null($cookieName)){
  91. $cookieName = $this->cookieName;
  92. }
  93. $ret = setcookie(
  94. $cookieName,
  95. null,
  96. (time()-1),
  97. $this->cookiePath,
  98. $this->cookieDomain
  99. );
  100. return $ret;
  101. }
  102. /**
  103. * クッキー名を設定します
  104. * @access public
  105. * @param string $name クッキー名
  106. * @returnmixed obj or bool false
  107. */
  108. public function setName($name=null)
  109. {
  110. if(!is_null($name)){
  111. $this->cookieName = $name;
  112. return $this;
  113. }
  114. $this->pushError('Cookie 名が null でした');
  115. return false;
  116. }
  117. /**
  118. * 設置cookie值
  119. * @access public
  120. * @param string $value cookie value
  121. * @return bool 文字列が文字列かどうか
  122. */
  123. public function setValue($value=null, $encrypt=false)
  124. {
  125. if(!is_null($value)){
  126. if(is_array($value)){
  127. $ value =serialize($value);
  128. }
  129. $data = ($encrypt?$this->cookieEncryption($value):base64_encode($value));
  130. $len = (function_exists('mb_strlen')?mb_strlen( $data):strlen($data));
  131. if($len>4096){
  132. $this->pushError('Cookie データが 4kb を超えています');
  133. return false;
  134. }
  135. $this->cookieData = $data;
  136. unset($data);
  137. return $this;
  138. }
  139. $this->pushError('Cookie 値が空でした');
  140. return false;
  141. }
  142. /**
  143. * Cookieの有効期限を設定します
  144. * @access public
  145. * @param string $time +1週間など
  146. * @return bool 文字列が文字列かどうか
  147. */
  148. public function setExpire($time=0)
  149. {
  150. $pre = substr($time,0,1);
  151. if(in_array($pre, array('+','-'))){
  152. $this- >cookieExpire = strtotime($time);
  153. return $this;
  154. } else {
  155. $this->cookieExpire = 0;
  156. return $this;
  157. }
  158. }
  159. /**
  160. * Cookieの保存パスを設定します
  161. * @access public
  162. * @param string $path
  163. * @return object $this
  164. */
  165. public function setPath($path='/')
  166. {
  167. $this->cookiePath = $path;
  168. return $this;
  169. }
  170. /**
  171. * Cookieが属するドメインを設定します
  172. * @access public
  173. * @param string $domain
  174. * @return object $this
  175. */
  176. public function setDomain($domain=null)
  177. {
  178. if(!is_null($domain)){
  179. $this->cookieDomain = $domain;
  180. }
  181. return $this;
  182. }
  183. /**
  184. *
  185. * @access public
  186. * @param bool $secure true/false
  187. * @return object $this
  188. */
  189. public function setSecure($secure =false)
  190. {
  191. $this->cookieSecure = (bool)$secure;
  192. return $this;
  193. }
  194. /**
  195. * HTTPOnly フラグ、まだすべてのブラウザで完全にはサポートされていません
  196. * @access public
  197. * @param bool $httponly yes/no
  198. * @return object $this
  199. */
  200. public function setHTTPOnly($httponly=false)
  201. {
  202. $ this->cookieHTTPOnly = (bool)$httponly;
  203. return $this;
  204. }
  205. /**
  206. * 指定されていない場合はルートドメインを取得するためのジェンキービット
  207. * @access private
  208. * @return string Le Domain
  209. */
  210. プライベート関数 getRootDomain()
  211. {
  212. $host = $_SERVER['HTTP_HOST'];
  213. $parts =explode('.', $host);
  214. if(count($parts)>1){
  215. $tld = array_pop($parts);
  216. $domain = array_pop($parts).'.'。 $tld;
  217. } else {
  218. $domain = array_pop($parts);
  219. }
  220. return '.'.$domain;
  221. }
  222. /**
  223. * 値の暗号化
  224. * @access private
  225. * @param string $str string to be (de|en)crypted
  226. * @param string $decrypt 復号化するかどうか
  227. * @return string (de|en)crypted string
  228. */
  229. プライベート関数 cookieEncryption($str=null, $decrypt=false)
  230. {
  231. if(is_null($str)){
  232. $this->pushError('null 文字列を暗号化/復号化できません');
  233. return $str;
  234. }

  235. < p> $iv_size = mcrypt_get_iv_size(MCRYPT_3DES, MCRYPT_MODE_ECB);
  236. $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
  237. $key_size = mcrypt_get_key_size(MCRYPT_3DES, MCRYPT_MODE_ECB);
  238. $key = substr(self::DES_KEY,0,$key_size);

  239. if($decrypt){

  240. $return = mcrypt_decrypt(MCRYPT_3DES, $key, Base64_decode($str), MCRYPT_MODE_ECB, $iv);
  241. } else {
  242. $return =base64_encode(mcrypt_encrypt(MCRYPT_3DES, $key, $str, MCRYPT_MODE_ECB) , $iv));
  243. }

  244. return $return;

  245. }
  246. /**
  247. * エラー配列にエラーを追加します
  248. * @access public
  249. * @param string $error
  250. * @return none
  251. */
  252. プライベート関数 PushError($error=null)
  253. {
  254. if(!is_null($error)){
  255. $this->errors[] = $ error;
  256. }
  257. return;
  258. }
  259. /**
  260. * エラーの取得
  261. * @access public
  262. * @return string エラー
  263. */
  264. public function getErrors()
  265. {
  266. return implode("
    ", $this->errors);
  267. }
  268. }

复制代

调用例:

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

  2. // サンプルデータ

  3. $array = array('foo' =>'バー','バー'=>'foo');
  4. $string = 'これは文字列です';

  5. $c = new Cookie();

  6. /*

  7. 创建一个加密的クッキー数组
  8. * /
  9. echo '

    暗号化された配列

    ';

  10. $start = microtime(true);

  11. $c->setName ('Example') // Cookie 名

  12. ->setValue($array,true) // 2 番目のパラメータ true、データを暗号化します
  13. ->setExpire('+1 hours') // 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. < p>echo print_r($cookie,true).'
    '.$bench.'秒
    ';

  21. /*

  22. 销毁cookie
  23. */
  24. //$c->destroyCookie('Example');

  25. 创建一クッキー字符串,直接浏览器关闭時失效
  26. */
  27. echo '

    通常の暗号化されていない文字列

    ';
  28. $start = マイクロタイム(true);
  29. $c->setName('Example1')
  30. ->setValue($string) // ここで 2 番目のパラメータを false に設定できます
  31. ->setExpire(0)
  32. ->setPath('/')
  33. ->setDomain('localhost')
  34. ->createCookie();

  35. $cookie = $c->getCookie('Example1');

  36. < p>$bench = sprintf('%.8f',(microtime(true)-$start));

  37. echo print_r($cookie,true).'
    「.$ベンチ」秒';

复制發


声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。