Image Which Changes According to Time


This is my 30 minute code project, something which can be usefull to forum users, where you can add image to your signature, or just you want image which changes according to daytime like background to your website, or promo image for breakfast, lunch or dinner event in your restaurant. Point is, usage for this is unlimeted and code provided is just skeleton, you can edit it in many ways, like adding admin panel and database.

I use this technique for forum signatures to randomize images in my signature, in some forums it won't work without .htaccess configuration, I will show how to set it up.

1) We need to ensure that we have GD library on our server.
to do this just make simple php file with content


And serch for "GD", and check if it is enabled.

2) We will need some .png images or any images, I will use .png in this tutorial. I choose 5 motocross helmets.

3) Create .php file, name it whatever you want, and create directory where to store images.

4) Code for php file:

//get current time seconds
$seconds = date('s');
//poor if statements
if ($seconds <= 11)
    $filename = './pic/moto1.png';
elseif ($seconds <= 23)
    $filename = './pic/moto2.png';
elseif ($seconds <= 35)
    $filename = './pic/moto3.png';
elseif ($seconds <= 47)
    $filename = './pic/moto4.png';
elseif ($seconds <= 59)
    $filename = './pic/moto5.png';

//Set the correct content type
header('content-type: image/png');

$percent = 0.3;

// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = 400;
$newheight = 400;

// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefrompng($filename);

// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

// Output and free memory
//the resized image will be 400x300

This code will output image which changes every 12 seconds, you can change if's and date function to get minutes/hours/year etc.

and here is the image, refresh page to see how it works:


to insert it in your website just use

<img src="script.php" />

but in some forums you won't be able to insert .php file as image, so you need to set up .htaccess file to rewrite script.php to script.jpg

to do so just add these lines to your htaccess file

Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule script.jpg script.php [L]

And that is it, you have image which dynamically changes according to time.