Change css value with php

You should actually not use a .css file and instead use a .php file acting as a .css file. Then you can just set the new color to a variable in the .php css file.

Rename your style.css file to style.php, then add the following to the top of the file:

<?php header("Content-type: text/css"); ?>

This line tells the browser that the file is CSS instead of HTML. In your HTML files, change the stylesheet references from style.css to style.php. For example:

<link rel="stylesheet" type="text/css"
 media="screen" href="style.php">

citation: http://www.barelyfitz.com/projects/csscolor/


Putting out a CSS file through PHP will add overhead to the server as you will have dynamic HTML and CSS to create. Given the 'cascading' nature of CSS, any inline style served in the HTML pages will override the CSS, so it's quite likely that you can simply add some inline styles into the pages already being served by PHP. Another option is to update the CSS using Javascript, here is one way to do this, but I don't believe this works in all browsers (I use this in Webkit on iOS):-

var cssStyle = getCSSRule('#styleName');
cssStyle.style.background = redfinedColour;

...using getCSSRule from here:-

http://www.hunlock.com/blogs/Totally_Pwn_CSS_with_Javascript


How I do it is have a content loader controller or script that will load images/css/js and pass them to the browser, you can also control the cache and create javascript dynamically, like the image lists in tinyMCE ect:

Heres an stripped down example but you get the idea.

<?php 
$filename = value passed from url


if(file_exists(SITE_ROOT.'/templates/'.$theme.'/css/'.basename($filename))==true){
    $fullpath=SITE_ROOT.'/templates/'.$theme.'/css/'.basename($filename);
    header("Content-type: text/css");
    $search=array('{SITE_URL}','{BACKGROUND}');
    $replace=array('http://example.com',get_option('backgroundchanges'));
    echo str_replace($search,$replace,file_get_contents($fullpath));
    die;
}else{
    die('CSS file does not exist!');
}

?>

Then have you css files with place holders replaced by your parameters:

#div{
background: #{BACKGROUND} url('{SITE_URL}/stripe.png') repeat;
}

Tags:

Css

Php