Home > Backend Development > PHP Tutorial > PHP cookie manipulation class

PHP cookie manipulation class

WBOY
Release: 2016-07-25 08:44:27
Original
935 people have browsed it
  1. class Cookie
  2. {
  3. /**
  4. * Decrypt encrypted cookies
  5. *
  6. * @param string $encryptedText
  7. * @return string
  8. */
  9. private static function _decrypt($encryptedText)
  10. {
  11. $key = Config::get('secret_key');
  12. $cryptText = base64_decode($encryptedText);
  13. $ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
  14. $iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
  15. $decryptText = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $cryptText, MCRYPT_MODE_ECB, $iv);
  16. return trim($decryptText);
  17. }
  18. /**
  19. * Encrypted cookies
  20. *
  21. * @param string $plainText
  22. * @return string
  23. */
  24. private static function _encrypt($plainText)
  25. {
  26. $key = Config::get('secret_key');
  27. $ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
  28. $iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
  29. $encryptText = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $plainText, MCRYPT_MODE_ECB, $iv);
  30. return trim(base64_encode($encryptText));
  31. }
  32. /**
  33. * Delete cookie
  34. *
  35. * @param array $args
  36. * @return boolean
  37. */
  38. public static function del($args)
  39. {
  40. $name = $args['name'];
  41. $domain = isset($args['domain']) ? $args['domain'] : null;
  42. return isset($_COOKIE[$name]) ? setcookie($name, '', time() - 86400, '/', $domain) : true;
  43. }
  44. /**
  45. * Get the value of the specified cookie
  46. *
  47. * @param string $name
  48. */
  49. public static function get($name)
  50. {
  51. return isset($_COOKIE[$name]) ? self::_decrypt($_COOKIE[$name]) : null;
  52. }
  53. /**
  54. * Set cookie
  55. *
  56. * @param array $args
  57. * @return boolean
  58. */
  59. public static function set($args)
  60. {
  61. $name = $args['name'];
  62. $value= self::_encrypt($args['value']);
  63. $expire = isset($args['expire']) ? $args['expire'] : null;
  64. $path = isset($args['path']) ? $args['path'] : '/';
  65. $domain = isset($args['domain']) ? $args['domain'] : null;
  66. $secure = isset($args['secure']) ? $args['secure'] : 0;
  67. return setcookie($name, $value, $expire, $path, $domain, $secure);
  68. }
  69. }
复制代码

PHP, Cookie


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template