Dynamic CSS via PHP
PHP can generate a style sheet and, if the browser accepts it, send a compressed page.
This method, as well as those relying on "bugs" or browser detection, is not without risks.
Making a dynamic style sheet
As Opera 6 and Konqueror do not support some CSS2 rules, we will make a valid dynamic style sheet using PHP.In css_1page.css, the following rule is not correctly interpreted:
#content a{
border:1px solid;
border-color:transparent;
border-bottom-color:#B2CFE9;
}
* #content a{
border:1px solid #D4E6FE;
}
html>body #content a{
border:1px solid;
border-color:transparent;
border-bottom-color:#B2CFE9;
}
Link with a transparent border
badly displayed by browsers that do not not support CSS2 because it uses inline style.
It should be your case.
<?php
header("Content-type: text/css; charset=iso-8859-1");
?>
In our style sheet (here css_dyn_1page.php) we will also add a few PHP instructions to modify the rule if the browser is Opera 4, 5 or 6, Konqueror and remove the hack hiding the rule to MSIE.
We will use the "User Agent" declared by the browser.
<?php
$UA=getenv("HTTP_USER_AGENT");
if (preg_match("#MSIE [4-7]|Opera( |/)[4-6]|Konqueror#i",$UA) && !preg_match("#Opera( |/)[7-9]#i",$UA))
{
echo "
#content a{
border:1px solid #D4E6FE;
}";
}
else
{
echo"
#content a{
border:1px solid;
border-color:transparent;
border-bottom-color:#B2CFE9;
}
";
}
?>
As in any PHP script, we could also get any information from a cookie, a variable, a MySQL table...
Thus, the browser identifier will affect the source and a website mirror.
Linking the stylesheet
Then we will replace the following code:<link rel="stylesheet" href="css/css1page.css" type="text/css" />
by
<link rel="stylesheet" href="css/css_dyn_1page.php" type="text/css" />
or, not to crash Netscape 4 or IE 4, by
<style type="text/css">
<!--
/*<![CDATA[*/
@import "css/css_dyn_1page.php";
/*]]>*/
-->
</style>
Sending the page in a compressed form
It is not difficult to send this page compressed.We will only have to add the following code at the beginning of our file:
<?php
ob_start ("ob_gzhandler");
header("Content-type: text/css; charset=iso-8859-1");
/*Optional part*/
header("Cache-Control: must-revalidate");
$use_cache = 3600 ; //how long our cached file will last in seconds
//set to 0 if you use a cookie or a variable...
$Expiration = "Expires: ".gmdate("D, d M Y H:i:s",time() + $use_cache)." GMT";
header($Expiration);
/*End of optional part*/
?>
Not all browsers accept this compression but, except Netscape 4, they will display the page correctly.
Here are some of the risks and a PHP solution when Apache modules (compression and file name rewriting) are not enabled.
Some pages of the site use dynamic CSS with variables, cookies or a session.