Reading Javascript created cookies on a server with PHP

April 20th, 2009 10:13am in cookies, css, javascript, jquery, php

You can switch stylesheets on our new site — and the client remembers which one was selected using a cookie set with jQuery. And to make the UI behave consistently, the site needs access to the contents of that jQuery set cookie, on the server, using PHP.

This turns out to be fairly straight forward with jQuery’s Cookie plugin. Here’s how we would set the preferred stylesheet to be blue:

$.cookie('style', 'blue', {path: '/', expires: 365 });

And to access the very same preference labelled “styleafter it has been set, on the next request, you simply tap into the global Cookie array in PHP like this:

$_COOKIE['style'];

The only thing that you need to remember is that the jQuery code plays with the client’s DOM directly, and stores values in the local cookie store immediately. The PHP array is only available when a request is made and is buried in the HEAD of the request.

See a demo?

Here’s a stand alone demo of the interaction between PHP and jQuery cookies that you can download and play with for yourself.

Flavor

Ten Seven, Interactive is a web studio in Minneapolis dedicated to helping you realize your design intentions accurately in XHTML.

Call 612 868 7884.
Send an email.
Follow on Twitter.

We use Basecamp, Highrise, Freshbooks and pair Networks to get things done!