Thursday, 21 October 2010

PHP code for reading cookies

In the PHP code that displays the template for this website we add the following code to the HEAD of the HTML page (inside the STYLE tags).


First for the font famliy:
if(isset($_COOKIE['fontfamily']) && $_COOKIE['fontfamily']) { echo " body { font-family: \"{$_COOKIE['fontfamily']}\"; }\n"; }
and for the display setting:
if(isset($_COOKIE['overflow']) && $_COOKIE['overflow']) { echo " #content { max-height: {$_COOKIE['overflow']}px; overflow: auto; }\n"; }
and so on for other values. You can see the extra CSS properties in the HEAD of each page by viewing the HTML source.
Because the cookies are set with a path of '/' they apply to all pages in this domain. And because we use a single template for every page the preferences you select will apply to the entire site.
The advantage of using JavaScript to set the cookies is that they're recognised by the browser immediately. If we submitted the form and used PHP to set the cookies then they wouldn't appear immediately in the $_COOKIE array as the browser hasn't yet told the server that it has them yet. That would happen on the next request.
To get around this you have to do something like the following:

The first command tells the browser to set the cookie, and the second adds it to the $_COOKIE array so our script (above) can see the value right away.

No comments:

Post a Comment