欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

PHP操作Cookie的类

程序员文章站 2022-05-18 23:41:22
...
  1. class Cookie
  2. {
  3. /**
  4. * 解密已经加密了的cookie
  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. * 加密cookie
  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. * 删除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. * 得到指定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. * 设置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
相关标签: PHP操作Cookie的类