📜 ⬆️ ⬇️

Use $ _COOKIE as $ _SESSION

The theme came from a distant childhood, when I was just starting to program, to understand the features of PHP. At that time, I was surprised at such an injustice: with the session it was possible to work as with a regular associative array ( $ _SESSION ), and for cookies it was necessary to use the setcookie () function. Then I gained experience and understood why it was done this way.
As time goes on and PHP does not stand still, it appeared such a beautiful thing as SPL , one of the features of which is to refer to the object as an array, i.e. implementation of the ArrayAccess interface.
And now I remembered my child's idea, the $ _COOKIE array , and implemented it:

<?php /*              */ $_COOKIE['lang'] = 'ru'; 


Implementation can be viewed under the cut

')
 <?php class CookieStorage implements ArrayAccess { //       const DEFAULT_EXPIRE_TIME = 1411200; // 2  //   private $_storage; //        $_COOKIE public function __construct($cookies) { $this->_storage = $cookies; } //   ArrayAccess     public function offsetExists ($offset) { return isset ($this->_storage[$offset]); } //   ArrayAccess    public function offsetUnset ($offset) { unset($this->_storage[$offset]); } //       public function offsetGet ($offset) { return $this->_storage[$offset]; } //      public function offsetSet ($offset, $value) { if( $this->_setCookie($offset, $value) ){ $this->_storage[$offset] = $value; } else{ trigger_error('Cookie value was not set', E_USER_WARNING); } } //    setcookie private function _setCookie( $name, $value, $expire = 0, $path = '/', $domain = false, $secure = false , $httponly = false ){ if (!headers_sent()){ if ($domain === false){ $domain = $_SERVER['HTTP_HOST']; } if( $expire == 0 ){ $expire = time() + self::DEFAULT_EXPIRE_TIME; } return setcookie ( $name, $value, $expire, $path, $domain, $secure, $httponly ); } return false; } } //        $_COOKIE = new CookieStorage( $_COOKIE ); 


What is good about this solution compared to the simple setcookie () function? Well, at a minimum, the recording goes simultaneously to the browser and the $ _COOKIE global array (sometimes you have to work with it even before reloading the page). In this embodiment, it is possible to set most of the default parameters and adjust these parameters. Using your class, you can add the necessary functionality depending on the specific conditions.

In any case, this is not a universal ideal solution. This is a bicycle, yes, this is my bicycle. This is an idea that, perhaps, will like% username% and it will develop to a comprehensive solution of any problem.

Source: https://habr.com/ru/post/134870/


All Articles