Return to Snippet

Revision: 15477
at July 7, 2009 07:18 by segdeha


Updated Code
/**
 * Author: Andrew Hedges, [email protected]
 * License: free to use, alter, and redistribute without attribution
 */

/**
 * Turn any object (e.g., an array) into a string you can save in a cookie
 * @param object $obj
 * @return string
 */
function cookie_encode($obj) {
	$value = json_encode($obj);
	$value = base64_encode($value);
	return $value;
}

/**
 * Turn a string encoded by cookie_encode back into an object
 * @param string $value
 * @return object
 */
function cookie_decode($value) {
	$value = base64_decode($value);
	$value = json_decode($value, true);
	return $value;
}

Revision: 15476
at July 7, 2009 07:14 by segdeha


Initial Code
/**
 * Turn any object (e.g., an array) into a string you can save in a cookie
 * @param object $obj
 * @return string
 */
function cookie_encode($obj) {
	$value = json_encode($obj);
	$value = base64_encode($value);
	return $value;
}

/**
 * Turn a string encoded by cookie_encode back into an object
 * @param string $value
 * @return object
 */
function cookie_decode($value) {
	$value = base64_decode($value);
	$value = json_decode($value, true);
	return $value;
}

Initial URL


Initial Description
This is a great way to save complex objects as cookie values. You can't just json_encode because commas are not legal in cookie values. Remember not to use this for anything too big because cookies have a 4KB limit.

Initial Title
cookie_encode & cookie_decode

Initial Tags
json

Initial Language
PHP