AdSense

Thursday, 29 August 2013

Header image depending on the time of day

I created a homepage where I wanted to change the header image depending on the time of day. In the daytime I wanted an image of a building by day, in the nighttime an image of the same building by night.

This can be done pretty easy with PHP.

At first the current time hast to be  stored in variable:

$time = date("G", time())

time() function returns the UNIX timestamp of the server. The UNIX timestamp is the number of seconds since 01.01.1979 at 1 AM. To get the timestamp to a "readable" format we use the date() function. The format is chose with the first paramter. "G" delivers the the hours without leading zero. A lot of other formats are possible, you can find them on this website.

The current hour is saved in the variable called $time. It is important to know that time is stored in UTC (coordinated universal time). I needed MEZ (or MESZ) so I had to add one (two) hours.

Now the header image can be chosen according to the current time:

if ($time > 7 && $time < 21 ) {
   $path = "http://yourserversdomain.de/images/header_day.jpg";
 }

else {
    $path = "http://yourserversdomain.de/images/header_night.jpg";
}

If the number of hours is greater than 7 and less than 21 (it is between 8:00 and 20:59) the path of the "day image" is stored to the variable $path - else the path of the "night image".


Then the image is embedded using HTML:

<img src="<?php echo $path; ?>" width="123" height="456" alt="" />


Of course you could also use this method for creating images depending on the weekday or the season.

No comments:

Post a Comment