CSS Variables Using PHP

The Sample CSS

copy/* globals */
* { margin:0; padding:0; }
body { color:$body_text_color; font-size:$body_font_size; }

The above is a sample css file that we’ve named “default.css”. For those that don’t know PHP, any string that begins with $ is a variable.

copy/* get the stylesheet */
$stylesheet = @is_file($_GET[‘stylesheet’]) && strtolower(substr(strrchr($file_name,’.’),1)) == ‘css’ ? $_GET[‘stylesheet’] : ‘default.css’;

/* set the header information */
//will be output as css
header(‘Content-type: text/css’);
//set an expiration date
$days_to_cache = 10;
header(‘Expires: ‘.gmdate(‘D, d M Y H:i:s’,time() + (60 * 60 * 24 * $days_to_cache)).’ GMT’);

/* set the dynamic information */
//default css variable information
$default = array(
‘body_font_size’ => ’16px’,
‘body_text_color’ => ‘#00f’

//red css variable information
$red = array(
‘body_font_size’ => ’10px’,
‘body_text_color’ => ‘#f00’

/* extract the propery array’s information */
extract($_GET[‘theme’] && ${$_GET[‘theme’]} ? ${$_GET[‘theme’]} : $default);

/* load in the stylesheet */
$content = preg_replace(‘/\$([\w]+)/e’,’$0′,@file_get_contents($stylesheet));

/* spit it out */
echo $content;

There’s a fair amount going on in the PHP above:

We check to see if a specific stylesheet is has been asked for. If not, we’ll use a default stylesheet template. In this case, the default template is “default.css”. We also check to make sure that the requested file is a “.css” file and that it file actually exists.
We set the header information, including: the content type, which is “text/css”, and an expiration date, which isn’t required but recommended for caching purposes.
We set keys and values of the variables we will use in our stylesheet theme. These key => values are stored in arrays so that we may have different themes. Above we have a “default” theme and a “red” theme. Note the differences in font size and text color.
We check to see if a specific theme has been asked for. If not, we use the $default theme. If the requested them doesn’t exist, we serve the default theme.
We read in the file content and replace any string beginning with “$” with the value specified in the PHP file’s theme.
We echo the output. Done.

The Usage


The Result

copy/* globals */
* { margin:0; padding:0; }
body { color:#00f; font-size:16px; }

Voila! Variables are replaced by their values in the output. That’s it!

By Rz Rasel Posted in Php

One comment on “CSS Variables Using PHP

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s