note 50617 added to function.setcookie

From: Date: Fri, 04 Mar 2005 19:41:40 +0000
Subject: note 50617 added to function.setcookie
Groups: php.notes 
Request: Send a blank email to php-notes+get-85945@lists.php.net to get a copy of this message
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; ?> ---- Manual Page -- http://www.php.net/manual/en/function.setcookie.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+50617 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+50617&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+50617&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+50617&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+50617&report=yes&reason=useless Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+50617&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+50617&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#85945) next »