Time Sensitive CSS with PHP

I was using this technique on my site for a while and realized that i actually liked the evening image you currently see in the header of my site.

The basic principle behind this tutorial is to allow a CSS file to be dynamic in the sense that it can use logic to define certain images or even colour schemes if you wish. The User will never see any JavaScrip so if they have Javascript dissabled your design will still come through.

For my example i used a div with the class of headerImage, simple enough. I then created a new PHP file and called it city.php.

If you try to include a a PHP file as a CSS link it will not work properly. You need to change the files header information.

we do this by using this line of code:


header("Content-type: text/css");


The next step:
We now need php to tell what time it is and then decide what image to load based on that time.


$hour = date('H'); // hour of the day, 24 hour clock

			if ($hour > 19 or $hour < 4) {
				$timepic = 'city-night';
			} elseif ($hour > 10) {
				$timepic = 'city-evening';
			} else {
				$timepic = 'city-morning';
			}

Simple enough.

Joining the code:
We made a variable named $timepic and assigned it a value based on the time. so we now need to insert that value in our CSS and then we are finished.


/* --- Header image according to time --- */
.headerImage {
	background-image: url(images/< ? echo $timepic; ?>.png);
	height: 170px;
	background-position: top;
	}

The < ? echo $timepic; ?> will print the image name beside the file extension thus completing out little Time Sensitive CSS and PHP Script.

Full Source:


&lt; ?php
header(&quot;Content-type: text/css&quot;);
$hour = date('H'); // hour of the day, 24 hour clock

			if ($hour &gt; 19 or $hour &lt; 4) {
				$timepic = 'city-night';
			} elseif ($hour &gt; 10) {
				$timepic = 'city-evening';
			} else {
				$timepic = 'city-morning';
			}
?&gt;
/* --- Header image according to time --- */
.headerImage {
	background-image: url(images/&lt; ? echo $timepic; ?&gt;.png);
	height: 170px;
	background-position: top;
	}

I would recommend keeping the amount of dynamic content to a minimum as it will mean the User will have to download the CSS file every time an update or change has been made to the sites CSS. For my use i just linked a separate CSS file to remove the need of downloading the whole site CSS file again.

Further Reading:
Php Headers
Php Date Manual

Signup for my mailing list

Receive other rambings like this on design, code, and some times food.