Timed based CSS stylesheet with PHP
A quick tutorial to change your CSS according to the time of the day
It’s been quite a long time since I last posted an article here at Jek2k.com.
On my company’s web site I’ve made a little PHP script to change the CSS stylesheet depending on the time of the day. We have a bright white theme for day time and a dark black one for night time and Sundays (when we are closed). This script was initially inspired by the beautiful Radiant Mars website.
Some of you have asked me how I made it, so here is the code:
<?php
// time based Css Swicth
$time = date("H");
$date = date("w");
if (!isset($_GET['css'])) {
if ($time >= 9 && $time < 18 && $date != 0) { ?>
<link rel="stylesheet" href="<?php bloginfo('stylesheet_directory'); ?>/styles/day.css" type="text/css" media="screen" />
<? } else { ?>
<link rel="stylesheet" href="<?php bloginfo('stylesheet_directory'); ?>/styles/night.css" type="text/css" media="screen" />
<? };
} else { ?>
<link rel="stylesheet" href="<?php bloginfo('stylesheet_directory'); ?>/styles/<?php echo $_GET['css']; ?>.css" type="text/css" media="screen" />
<? }; ?>
Looks easy, doesn’t it?
Let’s see it in detail.
First I’ve set up two variables to read the current time (hour) of the day and the current day (number, 0 = Sunday) of the week.
$time = date("H");
$date = date("w");
For more information about handling date and time with PHP, please see the PHP documentation.
Then we have a pretty simple IF clause to check if the current time is between 9AM and 6PM and today is not Sunday.
According to this clause, the correct CSS stylesheet is loaded.
if ($time >= 9 && $time < 18 && $date != 0) { ?>
<link rel="stylesheet" href="<?php bloginfo('stylesheet_directory'); ?>/styles/day.css" type="text/css" media="screen" />
<? } else { ?>
<link rel="stylesheet" href="<?php bloginfo('stylesheet_directory'); ?>/styles/night.css" type="text/css" media="screen" />
<? };
The last part is another IF clause, mainly for debug reasons.
It checks if we have added a variable to the page’s URL, ie. pagename.php?css=day. This way we can override the time check and load the desired CSS stylesheet directly. This is useful to test your CSS files without waiting for it to change.
That’s it. Pretty basic, but remember I’m just a designer!
Use the PHP date function to read other parameters and modify this script to change the CSS stylesheet according to seasons, holidays, day of the week or whatever you like.
This tutorial is provided as is. Please do not email me questions or support requests about the scripts contained in this page. Use the comments below instead. Thank you.
About this entry
You’re currently reading “Timed based CSS stylesheet with PHP,” an entry on jek2kdotcom
- Posted on:
- 03.05.2007 @ 11pm
- Categories:
- Web Development, Tutorials, PHP
5 Comments | View
Come on, leave your feedback!