Cookie.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace Qii\Library;
  3. /**
  4. * 设置Cookie,cookie内容将会被加密
  5. */
  6. class Cookie
  7. {
  8. const VERSION = '1.2';
  9. /**
  10. * @var string $prefix cookie保存的前缀
  11. */
  12. private $prefix = '_';
  13. /**
  14. * cookie的过期时间
  15. */
  16. private $expire = 86400;
  17. private $securityKey = 'qii.v.1.3';
  18. public function __construct()
  19. {
  20. return $this;
  21. }
  22. /**
  23. * 设置用于加密解码的密匙
  24. * @param $key
  25. */
  26. public function setSecurityKey($key)
  27. {
  28. $this->securityKey = $key;
  29. return $this;
  30. }
  31. /**
  32. * 设置cookie
  33. * @param string $name cookie名
  34. * @param string $val cookie值
  35. * @param int $expire 过期时间,默认为一天
  36. */
  37. public function set($name, $val, $expire = 0)
  38. {
  39. if ($expire <= 0) $expire = $this->expire;
  40. $crypt = new \Qii\Library\Crypt();
  41. $crypt->setSecurityKey($this->securityKey);
  42. $val = trim($crypt->encrypt(urlencode($val)));
  43. return setcookie($this->prefix . $name, $val, time() + $expire, '/');
  44. }
  45. /**
  46. * 获取cookie
  47. */
  48. public function get($name)
  49. {
  50. $val = isset($_COOKIE[$this->prefix . $name]) ? $_COOKIE[$this->prefix . $name] : (isset($_COOKIE[$name]) ? $_COOKIE[$name] : '');
  51. if (!$val) return '';
  52. $crypt = new \Qii\Library\Crypt();
  53. $crypt->setSecurityKey($this->securityKey);
  54. return trim(urldecode($crypt->decrypt($val)));
  55. }
  56. /**
  57. * decode str
  58. * @param $val
  59. * @return string
  60. */
  61. public function decode($val) {
  62. if (!$val) return '';
  63. $crypt = new \Qii\Library\Crypt();
  64. $crypt->setSecurityKey($this->securityKey);
  65. return trim(urldecode($crypt->decrypt($val)));
  66. }
  67. }