PHP Cookie Class (classic, worth collecting)

Source: Internet
Author: User
Tags decrypt set cookie setcookie sprintf tld
  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 (); Could chain this too, must is 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 a array, you'll need to unserialize the return

  20. */

  21. Class Cookie {
  22. Cookie encryption key value string, can be modified according to your own needs
  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 Set Domain
  35. * @access Public
  36. * @return None
  37. */
  38. Public Function __construct ()
  39. {
  40. $this->cookiedomain = $this->getrootdomain ();
  41. }
  42. /**
  43. * Get Cookie value
  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 cookies
  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. * Clear Cookies
  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. * Set Cookie Value
  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 the expiration time of the 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. * Set the save path of the 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. * 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::D es_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. }

Copy Code

Invocation Example:

  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. Create an array of encrypted cookies
  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. Destroying cookies
  23. */
  24. $c->destroycookie (' Example ');

  25. /*

  26. Create a cookie string that fails when the browser is closed directly
  27. */
  28. Echo '

    Regular unencrypted string

    ';
  29. $start = Microtime (true);
  30. $c->setname (' Example1 ')
  31. ->setvalue ($string)//Second Param could is 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 ';

Copy Code
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.