Cookie.Class.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace Mall\Framework\Core;
  3. class Cookie
  4. {
  5. private $prefix = '';
  6. private $path = '/';
  7. private $domain = '';
  8. private static $_instance;
  9. public function __clone()
  10. {
  11. trigger_error('Clone is not allow!', E_USER_ERROR);
  12. }
  13. public static function getInstance($options = [])
  14. {
  15. $options = $options ?: Config::getInstance()->get('cookie');
  16. if (!self::$_instance instanceof self) {
  17. self::$_instance = new self;
  18. self::$_instance->setOptions($options);
  19. }
  20. return self::$_instance;
  21. }
  22. public function setOptions($options)
  23. {
  24. $this->prefix = $options['prefix'];
  25. $this->path = $options['path'];
  26. $this->domain = $options['domain'];
  27. }
  28. /**
  29. * 设置一个cookie值
  30. *
  31. * @param string $var
  32. * @param mixed $value
  33. * @param int $time 存活时间
  34. */
  35. public function set($var, $value = null, $time = 0)
  36. {
  37. if (is_null($value)) {
  38. $time = time() - 3600;
  39. } elseif ($time > 0 && $time < 31536000) {
  40. $time += time();
  41. }
  42. $s = $_SERVER['SERVER_PORT'] == '443' ? 1 : 0;
  43. $var = $this->prefix . $var;
  44. $_COOKIE[$var] = $value;
  45. if (is_array($value)) {
  46. foreach ($value as $k => $v) {
  47. setcookie($var . '[' . $k . ']', $v, $time, $this->path, $this->domain, $s);
  48. }
  49. } else {
  50. setcookie($var, $value, $time, $this->path, $this->domain, $s);
  51. }
  52. }
  53. /**
  54. * @param $var
  55. * @return bool
  56. */
  57. public function get($var)
  58. {
  59. $var = $this->prefix . $var;
  60. return isset($_COOKIE[$var]) ? $_COOKIE[$var] : false;
  61. }
  62. }