Saturday, December 31, 2011

Global variables for CSS


Purpose: Create a CSS template file demo.txt with global variables, after processed by a PHP file convert_to_css.php, a CSS file demo.css is produced. So we can easily manage complicated CSS files.

demo.txt:

$colour2 = '#363';

body{
    text-align:center;
    background:$colour2;
}
#boundary{
    background:$colour2;
}

convert_to_css.php
<?PHP
ini_set('display_errors', 1);
error_reporting(E_ALL);
// grab the c parameter and ensure that it contains .txt is no slashes
// this is a safety measure to prevent XSS
//http://icant.co.uk/articles/cssconstants/
$c=$_GET['file'];
if(preg_match('/\//',$c) or !preg_match('/.txt/',$c))
{
    die('only local CSS files allowed!');
    exit;
}

// load the content of the CSS file into the variable css, end if the
// file wasn't found.
$css=load($c);
if($css=='')
{
    die('File not Found, sorry!');
    exit;
}
// grab all constants and store them in the array constants
preg_match_all("/\\$(\w+).*=.*\'(.*)\'/",$css,$constants);
for($i=0;$i<sizeof($constants[1]);$i++)
{

// replace all occurrences of the contants with their values
    $css=preg_replace('/\\$'.$constants[1][$i].'/',$constants[2][$i],$css);
}

// delete all constant definitions
$css=preg_replace("/\\#.*=.*?;\s+/s",'',$css);

$newfile=str_replace(".txt",".css",$c);
// save the style sheet
save($newfile, $css);
echo 'convert to '.$newfile;
function load($filelocation)
{
    if (file_exists($filelocation))
    {
        $newfile = fopen($filelocation,"r");
        $file_content = fread($newfile, filesize($filelocation));
        fclose($newfile);
        return $file_content;
    }
}
function save($newfile, $filecontent)
{
$file = fopen ($newfile, "w");
fwrite($file, $filecontent);
fclose ($file); 
}
?>
After run convert_to_css.php?file=demo.txt
 demo.css is produced:
body{
    text-align:center;
    background:#363;
}
#boundary{
 
    background:#363;
}
Reference:
http://icant.co.uk/articles/cssconstants/

No comments:

Post a Comment