note 24337 added to function.setcookie

From: Date: Tue, 13 Aug 2002 17:13:33 +0000
Subject: note 24337 added to function.setcookie
Groups: php.notes 
Request: Send a blank email to php-notes+get-34943@lists.php.net to get a copy of this message
I wrote a class to help manage cookies. It stores all of the values in a single serialized, base64_encoded cookie and can add and delete individual values without having to delete the whole cookie. The class is listed below, with some sample code to demonstrate the functionality: // class for setting, deleting, and retrieving cookies // written by Brandon Tallent <djresonance@yahoo.com> class cCookie { var $values; var $_expire; var $_name; var $_path; var $_debug; function cCookie($name = 'MY_COOKIE', $path = '/') { $this->get_cookie($name); $this->set_expire(2678400); // default expire time of 31 days $this->set_name($name); $this->set_path($path); $this->_debug = false; } // adds a value to the cookie function add($name, $value) { $this->values[$name] = $value; } // deletes the specified value (name) from the cookie function delete($name) { unset($this->values[$name]); } // retrieves the cookie and unserializes it back into an array function get_cookie($name) { global $HTTP_COOKIE_VARS; if (isset($HTTP_COOKIE_VARS[$name])) { $this->values = unserialize(base64_decode($HTTP_COOKIE_VARS[$name])); } } // permanently removes a cookie function perm_delete($name) { $cookie = base64_encode(serialize($this->values)); if (!setcookie($this->_name, $cookie, time()-$this->_expire)) { die('Cookie failed to send!'); } } // sends the cookie to the user function send() { $cookie = base64_encode(serialize($this->values)); if (!setcookie($this->_name, $cookie, time()+$this->_expire)) { die('Cookie failed to send!'); } if ($this->_debug) { echo "setcookie($this->_name, $cookie, $this->_expire)<br>"; } } function set_expire($expire) { $this->_expire = $expire; } function set_name($name) { $this->_name = $name; } function set_path($path) { $this->_path = $path; } } // to add a new cookie with some values: $cookie = new cCookie; $cookie->add('my_var', 10); $cookie->add('test', 20); $cookie->send(); // to get the values on another page: $cookie = new cCookie; print_r($cookie->values); // the output of print_r would be // Array ( [my_var] => 10 [test] => 20 ) // to delete the 'test' variable from the cookie $cookie = new cCookie; $cookie->delete('test'); // to permanently delete the cookie $cookie = new cCookie; $cookie->perm_delete(); ----- Hope this helps. -- http://www.php.net/manual/en/function.setcookie.php http://master.php.net/manage/user-notes.php?action=edit+24337 http://master.php.net/manage/user-notes.php?action=delete+24337 http://master.php.net/manage/user-notes.php?action=reject+24337

« previous php.notes (#34943) next »