Easy PHP Cookies
I was working on a security subsystem for a website the other day, and I needed to encode a bunch of variables into a cookie. I’ve written this kind of code way too many times before, and it’s pretty straightforward. It is very tedious, however, and can get complicated if you have to worry about escaping characters, encoding arrays, etc.
With this in mind, I decided to sniff around in the PHP documentation and see if there was something there that I could use to make this easier. I started looking at serialization, followed a few references, and pretty soon I came up with a very simple solution:
// Encode the values and set a cookie
function encode_cookie ($foo, $bar, $snork)
{
$cookie = serialize(compact("foo", "bar", "snork"));
setcookie("name", $cookie, 0, "/", "ericwinkelman.com");
}
// Get the cookie, and decode the values
function decode_cookie (&$foo, &$bar, &$snork)
{
extract(unserialize($_COOKIE["name"]));
}
The key to this code is the compact and extract functions. These functions work directly with the program’s symbol table, and not the variables themselves. The compact function takes the names of the variables to store in the cookie, and looks up the values in the symbol table. Similarly, the extract function gets the variable names and values from the cookie, and updates the symbol table with this information.
Through these functions, you don’t have to worry about formating, parsing, escaping, variable orders, etc. It even works with arrays. You must, however, make sure that the names of the function parameters are the same between the encode_cookie and decode_cookie functions.
For extra credit, I suggest encrypting the cookie value so that site visitors can’t mess around with them. Michael Gracie recently posted encryption and decryption functions that can be used for this.
Bake at 450 for 10 minutes and cool slightly before serving…
Posted: February 18th, 2009 | Filed under: Coding | Tags: cookies, php | No Comments »