note 14077 modified in function.setcookie by john

From: Date: Sat, 30 Nov 2002 16:20:57 +0000
Subject: note 14077 modified in function.setcookie by john
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-40159@lists.php.net to get a copy of this message
[Editor's Note: setcookie() automatically calls urlencode/decode -- doing it manually is unnecessary] To store an object as a cookie, I use the following: function object_to_cookie($obj) { $z = serialize($obj); $z = gzcompress($z); $z = base64_encode($z); $z = urlencode($z); return $z; } function cookie_to_object($cookie) { $z = urldecode($cookie); $z = base64_decode($z); $z = gzuncompress($z); $z = unserialize($z); return $z; } I don't think the urlencode()/urldecode() is strictly necessary (I only use it because '/' is part of the base64 alphabet and I'm paranoid). But this works well, and allows you to encode a lot of information into a single cookie instead of using multiple cookies; you can have something like a UserPrefs object that encapsulates all user-specific information, and set that as a single cookie. --was-- To store an object as a cookie, I use the following: function object_to_cookie($obj) { $z = serialize($obj); $z = gzcompress($z); $z = base64_encode($z); $z = urlencode($z); return $z; } function cookie_to_object($cookie) { $z = urldecode($cookie); $z = base64_decode($z); $z = gzuncompress($z); $z = unserialize($z); return $z; } I don't think the urlencode()/urldecode() is strictly necessary (I only use it because '/' is part of the base64 alphabet and I'm paranoid). But this works well, and allows you to encode a lot of information into a single cookie instead of using multiple cookies; you can have something like a UserPrefs object that encapsulates all user-specific information, and set that as a single cookie. http://www.php.net/manual/en/function.setcookie.php

« previous php.notes (#40159) next »