목차
Encrypted array
Regular unencrypted string
백엔드 개발 PHP 튜토리얼 php cookie类(经典,值得收藏)

php cookie类(经典,值得收藏)

Jul 25, 2016 am 08:56 AM

  1. /**

  2. --- CREATE COOKIE OBJECT ---
  3. $c = new cookie();
  4. --- CREATE/UPDATE COOKIE ---
  5. $c->setName('myCookie') // REQUIRED
  6. ->setValue($value,true) // REQUIRED - 1st param = data string/array, 2nd param = encrypt (true=yes)
  7. ->setExpire('+1 hour') // optional - defaults to "0" or browser close
  8. ->setPath('/') // optional - defaults to /
  9. ->setDomain('.domain.com') // optional - will try to auto-detect
  10. ->setSecure(false) // optional - default false
  11. ->setHTTPOnly(false); // optional - default false
  12. $c->createCookie(); // you could chain this too, must be last
  13. --- DESTROY COOKIE ---
  14. $c->setName('myCookie')->destroyCookie();
  15. OR
  16. $c->destroyCookie('myCookie');
  17. --- GET COOKIE ---
  18. $cookie = $c->getCookie('myCookie',true); // 1st param = cookie name, 2nd param = whether to decrypt
  19. // if the value is an array, you'll need to unserialize the return
  20. */

  21. Class Cookie {
  22. // cookie加密键值串,可以根据自己的需要修改
  23. const DES_KEY = 'o89L7234kjW2Wad72SHw22lPZmEbP3dSj7TT10A5Sh60';
  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 cookie to be retrieved
  46. * @param bool $decrypt whether to decrypt the values
  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 name was 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. * 设置cookie名称
  104. * @access public
  105. * @param string $name cookie name
  106. * @return mixed 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 name was null');
  115. return false;
  116. }
  117. /**
  118. * 设置cookie值
  119. * @access public
  120. * @param string $value cookie value
  121. * @return bool whether the string was a string
  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 data exceeds 4kb');
  133. return false;
  134. }
  135. $this->cookieData = $data;
  136. unset($data);
  137. return $this;
  138. }
  139. $this->pushError('Cookie value was empty');
  140. return false;
  141. }
  142. /**
  143. * 设置cookie的过期时间
  144. * @access public
  145. * @param string $time +1 week, etc.
  146. * @return bool whether the string was a string
  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 flag, not yet fully supported by all browsers
  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. * Jenky bit to retrieve root domain if not supplied
  207. * @access private
  208. * @return string Le Domain
  209. */
  210. private function 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. * Value Encryption
  224. * @access private
  225. * @param string $str string to be (de|en)crypted
  226. * @param string $decrypt whether to decrypt or not
  227. * @return string (de|en)crypted string
  228. */
  229. private function cookieEncryption($str=null, $decrypt=false)
  230. {
  231. if(is_null($str)){
  232. $this->pushError('Cannot encrypt/decrypt null string');
  233. return $str;
  234. }
  235. $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. * Add error to errors array
  248. * @access public
  249. * @param string $error
  250. * @return none
  251. */
  252. private function pushError($error=null)
  253. {
  254. if(!is_null($error)){
  255. $this->errors[] = $error;
  256. }
  257. return;
  258. }
  259. /**
  260. * Retrieve errors
  261. * @access public
  262. * @return string errors
  263. */
  264. public function getErrors()
  265. {
  266. return implode("
    ", $this->errors);
  267. }
  268. }
复制代码

调用示例:

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

  2. // Sample data

  3. $array = array('foo'=>'bar','bar'=>'foo');
  4. $string = 'this is a string';
  5. $c = new Cookie();

  6. /*

  7. 创建一个加密的cookie数组
  8. */
  9. echo '

    Encrypted array

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

  11. $c->setName('Example') // our cookie name

  12. ->setValue($array,true) // second parameter, true, encrypts data
  13. ->setExpire('+1 hours') // expires in 1 hour
  14. ->setPath('/') // cookie path
  15. ->setDomain('localhost') // set for localhost
  16. ->createCookie();
  17. $cookie = $c->getCookie('Example',true);
  18. $cookie = unserialize($cookie);
  19. $bench = sprintf('%.8f',(microtime(true)-$start));

  20. echo print_r($cookie,true).'
    '.$bench.' seconds


    ';
  21. /*

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

  26. 创建一个cookie字符串,直接浏览器关闭时失效
  27. */
  28. echo '

    Regular unencrypted string

    ';
  29. $start = microtime(true);
  30. $c->setName('Example1')
  31. ->setValue($string) // Second param could be set to false here
  32. ->setExpire(0)
  33. ->setPath('/')
  34. ->setDomain('localhost')
  35. ->createCookie();
  36. $cookie = $c->getCookie('Example1');

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

  38. echo print_r($cookie,true).'
    '.$bench.' seconds';

复制代码


본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

11 최고의 PHP URL 쇼트너 스크립트 (무료 및 프리미엄) 11 최고의 PHP URL 쇼트너 스크립트 (무료 및 프리미엄) Mar 03, 2025 am 10:49 AM

종종 키워드와 추적 매개 변수로 혼란스러워하는 긴 URL은 방문자를 방해 할 수 있습니다. URL 단축 스크립트는 솔루션을 제공하여 소셜 미디어 및 기타 플랫폼에 이상적인 간결한 링크를 만듭니다. 이 스크립트는 개별 웹 사이트 a에 유용합니다

Instagram API 소개 Instagram API 소개 Mar 02, 2025 am 09:32 AM

Instagram은 2012 년 Facebook에서 유명한 인수에 이어 타사 사용을 위해 두 개의 API 세트를 채택했습니다. Instagram Graph API 및 Instagram Basic Display API입니다. 개발자는

Laravel의 플래시 세션 데이터로 작업합니다 Laravel의 플래시 세션 데이터로 작업합니다 Mar 12, 2025 pm 05:08 PM

Laravel은 직관적 인 플래시 방법을 사용하여 임시 세션 데이터 처리를 단순화합니다. 응용 프로그램에 간단한 메시지, 경고 또는 알림을 표시하는 데 적합합니다. 데이터는 기본적으로 후속 요청에만 지속됩니다. $ 요청-

Laravel Back End : Part 2, React가있는 React 앱 구축 Laravel Back End : Part 2, React가있는 React 앱 구축 Mar 04, 2025 am 09:33 AM

이것은 Laravel 백엔드가있는 React Application을 구축하는 데있어 시리즈의 두 번째이자 마지막 부분입니다. 이 시리즈의 첫 번째 부분에서는 기본 제품 목록 응용 프로그램을 위해 Laravel을 사용하여 편안한 API를 만들었습니다. 이 튜토리얼에서는 Dev가 될 것입니다

Laravel 테스트에서 단순화 된 HTTP 응답 조롱 Laravel 테스트에서 단순화 된 HTTP 응답 조롱 Mar 12, 2025 pm 05:09 PM

Laravel은 간결한 HTTP 응답 시뮬레이션 구문을 제공하여 HTTP 상호 작용 테스트를 단순화합니다. 이 접근법은 테스트 시뮬레이션을보다 직관적으로 만들면서 코드 중복성을 크게 줄입니다. 기본 구현은 다양한 응답 유형 단축키를 제공합니다. Illuminate \ support \ Facades \ http를 사용하십시오. http :: 가짜 ([ 'google.com'=> ​​'Hello World', 'github.com'=> ​​[ 'foo'=> 'bar'], 'forge.laravel.com'=>

PHP의 컬 : REST API에서 PHP Curl Extension 사용 방법 PHP의 컬 : REST API에서 PHP Curl Extension 사용 방법 Mar 14, 2025 am 11:42 AM

PHP 클라이언트 URL (CURL) 확장자는 개발자를위한 강력한 도구이며 원격 서버 및 REST API와의 원활한 상호 작용을 가능하게합니다. PHP CURL은 존경받는 다중 프로모토콜 파일 전송 라이브러리 인 Libcurl을 활용하여 효율적인 execu를 용이하게합니다.

Codecanyon에서 12 개의 최고의 PHP 채팅 스크립트 Codecanyon에서 12 개의 최고의 PHP 채팅 스크립트 Mar 13, 2025 pm 12:08 PM

고객의 가장 긴급한 문제에 실시간 인스턴트 솔루션을 제공하고 싶습니까? 라이브 채팅을 통해 고객과 실시간 대화를 나누고 문제를 즉시 해결할 수 있습니다. 그것은 당신이 당신의 관습에 더 빠른 서비스를 제공 할 수 있도록합니다.

2025 PHP 상황 조사 발표 2025 PHP 상황 조사 발표 Mar 03, 2025 pm 04:20 PM

2025 PHP Landscape Survey는 현재 PHP 개발 동향을 조사합니다. 개발자와 비즈니스에 대한 통찰력을 제공하는 프레임 워크 사용, 배포 방법 및 과제를 탐색합니다. 이 조사는 현대 PHP Versio의 성장을 예상합니다

See all articles