note 50617 deleted from function.setcookie by bjori

From: Date: Mon, 08 Jan 2007 10:43:46 +0000
Subject: note 50617 deleted from function.setcookie by bjori
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-121423@lists.php.net to get a copy of this message
Note Submitter: dear_grommet at reverse dot liamtoh dot moc ---- When using cookies to store PHP variables with serialize(), I found that I also needed to use stripslashes(). Here is an example of code that does what the PHP web site does - remembering your last search options at the top of the page. I would initialise my variable $cookie_data to whatever I wanted, and I use an array, eg: <?php // user options held in persistant cookies $cookie_data['hist_days'] = 15; $cookie_data['test1'] = "a string test $ ; \" & "; $cookie_data['test2'] = 0; $cookie_data_expire = 60 * 60 * 24 * 60; ?> And then this code, run at the start of the script, after the session_start(), will store/restore this cookie data... <?php // restore user options if (isset($_SESSION['cookie_data'])) { // from session data $cookie_data = $_SESSION['cookie_data']; } else { // from cookie if (isset($_COOKIE['cookie_data'])) { $string = $_COOKIE['cookie_data']; $string = stripslashes($string); //$string = gzuncompress($string); $cookie_data = unserialize($string); } } ?> NB. I found that for such a small amount of data, the gzcompress() made the string bigger. The idea is that if the $_SESSION data is available, then it takes precedence, but if not, then it will re-load the last values from a cookie that was stored (for the last 60 days). Then you need to get any user changes for any values and copy them back into the $_SESSION data. Then set both the $_SESSION and cookie data., eg: <?php // get new user options $cookie_data['test2']++; $_SESSION['cookie_data'] = $cookie_data; // store in cookie $string = serialize($cookie_data); //$string = gzcompress($string, 9); setcookie('cookie_data', $string, time()+$cookie_data_expire, '/'); // store in session $_SESSION['cookie_data'] = $cookie_data; ?>

« previous php.notes (#121423) next »