Cookie Wrapper with name domain


/ Published in: PHP
Save to your folder(s)

Easy and lazy way to use cookie in PHP5


Copy this code and paste it in your HTML
  1. class Cookie
  2. {
  3. var $__setting;
  4.  
  5. function __construct($name = 'FuseLogic',$live = 31104000)
  6. {
  7. $this->__setting = new open();
  8. $this->__setting->name = $name;
  9. $this->__setting->_cookies = array();
  10. $this->__setting->space = '___';
  11.  
  12. $this->setDomain();
  13. $this->setPath();
  14. $this->setLive($live);
  15.  
  16. if(is_array($_COOKIE))
  17. {
  18. foreach($_COOKIE as $k =>$v)
  19. {
  20. $temp = explode($this->__setting->space,$k);
  21. if($temp[0] == $this->__setting->name)
  22. {
  23. $k = str_replace($this->__setting->name.$this->__setting->space,'',$k);
  24. $this->__setting->_cookies[$k] = $v;
  25. }
  26. }
  27. }
  28. }
  29.  
  30. function setDomain($domain = '')
  31. {
  32. $this->__setting->domain = $domain;
  33. }
  34.  
  35. function setLive($time = 3600)
  36. {
  37. $this->__setting->live = (int) $time;
  38. }
  39.  
  40. function setPath($path = '/')
  41. {
  42. $this->__setting->path = $path;
  43. }
  44.  
  45. function name($name = null)
  46. {
  47. return $this->__setting->name.$this->__setting->space.$name;
  48. }
  49.  
  50. public function __get($name)
  51. {
  52. return $this->__setting->_cookies[$name];
  53. }
  54.  
  55. public function __set($name,$value)
  56. {
  57. $this->__setting->_cookies[$name] = $value;
  58. $name = $this->name($name);
  59. $_COOKIE[$name] = $value;
  60. if($value == null)
  61. {
  62. setcookie($name,$value,time()-$this->__setting->live,$this->__setting->path,$this->__setting->domain,0);
  63. }else
  64. {
  65. setcookie($name,$value,time()+$this->__setting->live,$this->__setting->path,$this->__setting->domain,0);
  66. }
  67. }
  68.  
  69. public function __isset($name)
  70. {
  71. return isset($this->__setting->_cookies[$name]);
  72. }
  73.  
  74. function clean()
  75. {
  76. foreach($this->__setting->_cookies as $name => $value)
  77. {
  78. $name = $this->name($name);
  79. setcookie($name,$value,time()-$this->__setting->live,$this->__setting->path,$this->__setting->domain,0);
  80. @$_COOKIE[$name] = null;
  81. }
  82. $this->__setting->_cookies = array();
  83. }
  84.  
  85. function cleanAll()
  86. {
  87. foreach($_COOKIE as $name => $value)
  88. {
  89. setcookie($name,$value,time()-$this->__setting->live,$this->__setting->path,$this->__setting->domain,0);
  90. }
  91. @$_COOKIE = array();
  92. }
  93.  
  94. function toArray()
  95. {
  96. return $this->__setting->_cookies;
  97. }
  98.  
  99. function fromArray($a = null)
  100. {
  101. if(is_array($a))
  102. {
  103. foreach($a as $k => $v ) $this->$k = $v;
  104. }
  105. }
  106.  
  107. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.