search
HomeBackend DevelopmentPHP Tutorialphp cookie class (classic, worth collecting)

  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. * Constructor sets the domain
  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. * Create 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. * Set cookie name
  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. * Set cookie expiration time
  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. * Set the cookie saving path
  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. * Set the domain to which the cookie belongs
  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';

复制代码


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software