Phpcookie class (classic, worthy of favorites)

Source: Internet
Author: User
Tags tld
Phpcookie class (classic, worthy of favorites)

  1. /**

  2. --- Create cookie object ---
  3. $ C = new cookie ();
  4. --- CREATE/update cookie ---
  5. $ C-> setName ('mycooker') // 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/
  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 cocould chain this too, must be last
  13. --- Destroy cookie ---
  14. $ C-> setName ('mycooker')-> destroyCookie ();
  15. OR
  16. $ C-> destroyCookie ('mycooker ');
  17. --- Get cookie ---
  18. $ Cookie = $ c-> getCookie ('mycooker', 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 encryption key value string, which can be modified as needed
  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 setting domain
  35. * @ Access public
  36. * @ Return none
  37. */
  38. Public function _ construct ()
  39. {
  40. $ This-> cookieDomain = $ this-> getRootDomain ();
  41. }
  42. /**
  43. * Obtain the 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 a 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. * 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 the 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 the 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 & gt; 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 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 storage 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 ('could not 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. }

Call 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 encrypted cookie array
  8. */
  9. Echo 'encryption 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. $ Duration = sprintf ('%. 8f', (microtime (true)-$ start ));

  20. Echo print_r ($ cookie, true ).'
    '. $ Seconds.' seconds

    ';

  21. /*

  22. Destroy cookie
  23. */
  24. // $ C-> destroyCookie ('example ');

  25. /*

  26. Create a cookie string, which becomes invalid when the browser is closed.
  27. */
  28. Echo 'regular unencrypted string ';
  29. $ Start = microtime (true );
  30. $ C-> setName ('example1 ')
  31. -> SetValue ($ string) // Second param cocould be set to false here
  32. -> SetExpire (0)
  33. -> SetPath ('/')
  34. -> SetDomain ('localhost ')
  35. -> CreateCookie ();

  36. $ Cookie = $ c-> getCookie ('example1 ');

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

  38. Echo print_r ($ cookie, true ).'
    '. $ Queue. 'seconds ';

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.