Software, your way.
burger menu icon
WillMaster

WillMaster > LibraryWebsite Automation

FREE! Coding tips, tricks, and treasures.

Possibilities weekly ezine

Get the weekly email website developers read:

 

Your email address

name@example.com
YES! Send Possibilities every week!

The Easiest Image Rotator Ever

If you've been reluctant to install an image rotator because it felt like it would be complicated, here is one that's easy to install and easy to use.

With this one:

  1. No dashboard or control panel.

  2. Publish images on your web page with a line of either JavaScript or PHP code, your choice.

  3. Images can be selected randomly or rotated through available images, your choice.

(Without the choices, the software could be made even simpler. They're available because you might want them.)

I'll talk about the choices later in the article. Right now, let me describe how easy it really is to install this.

You make a separate subdirectory on your server. In that subdirectory, you:

  1. Upload the images you want to rotate.

  2. Upload the PHP script that comes with this article. (Upload as is. No customization required.)

On your web pages, where you want the images to be published, insert your choice of either a line of JavaScript or a line of PHP code.

It's installed.

When the PHP script selects an image to publish, it selects from all the image files in that subdirectory.

At any time, you can replace, upload, and delete images from the subdirectory. The PHP script will automatically accommodate.

Here is a live demo. Images are rotated, the next image in line published whenever the page is loaded.

Image of coloradoriver2.jpg

In a moment, I'll describe how to format the line of JavaScript or PHP code you'll use to publish the images. And how to choose the type of selection, random or rotate. WordPress instructions are included.

But first, here's the source code of the PHP script (information follows).

<?php
/*
   Easiest Image Rotator
   Version 1.0
   June 17, 2017

   Will Bontrager Software LLC
   https://www.willmaster.com/
   Copyright 2017 Will Bontrager Software LLC

   This software is provided "AS IS," without 
   any warranty of any kind, without even any 
   implied warranty such as merchantability 
   or fitness for a particular purpose.
   Will Bontrager Software LLC grants 
   you a royalty free license to use or 
   modify this software provided this 
   notice appears on all copies. 
*/
# No customization required.
# Accompanying article has instructions.
if( ! ini_get('date.timezone') ) { date_default_timezone_set('UTC'); }
mb_internal_encoding('UTF-8');
ini_set('display_errors',1);
error_reporting(E_ALL);
$RotationMonitoringFile = './last-rotated.txt';
if( isset($_GET['test']) and $_GET['test'] ) { DoFileCreateUpdateTests(); }
$imageURL = ((isset($_SERVER['HTTPS']) and $_SERVER['HTTPS'])?'https://':'http://') . $_SERVER['HTTP_HOST'] . preg_replace('/^'.preg_quote($_SERVER['DOCUMENT_ROOT'],'/').'/','',(__DIR__.'/'));
$fileList = array();
foreach( glob('*') as $file )
{
   if( preg_match('/\.(gif|jpg|jpeg|png)$/i',$file) ) { $fileList[] = $file; }
}
$imageFile = '';
$count = count($fileList);
if( ! $count ) { ReturnContentAndExit('No Images Found.'); }
if( isset($_GET['rotate']) and $_GET['rotate'] )
{
   if( ! file_exists($RotationMonitoringFile) ) { file_put_contents($RotationMonitoringFile,'0   '); }
   $f = fopen($RotationMonitoringFile,'rw+');
   $index = intval(fgets($f))+1;
   if( $index > $count ) { $index = 1; }
   fseek($f,0);
   fwrite($f,"$index ");
   fclose($f);
   $imageFile = $fileList[($index-1)];
}
else { $imageFile = $fileList[mt_rand(0,($count-1))]; }
ReturnContentAndExit("<img src='$imageURL$imageFile' style='max-width:100%; height:auto;' alt='Image of $imageFile'>");

function ReturnContentAndExit($content)
{
   if( isset($_GET['js']) and $_GET['js'] )
   {
      header('Content-type: text/javascript');
      $content = str_replace('"',"\\".'"',$content);
      $content = preg_replace('/(scri)(pt)/i','$1"+"$2',$content);
      $content = 'document.write("' . $content . '");';
   }
   echo $content;
   exit;
} # function ReturnContentAndExit()

function DoFileCreateUpdateTests()
{
   global $RotationMonitoringFile;
   $filename = preg_replace('!^.*/!','',$RotationMonitoringFile);
   echo '<pre>';
   if( file_exists($RotationMonitoringFile) ) { echo "File $filename exists.\n"; }
   else
   {
      $f = fopen($RotationMonitoringFile,'w');
      if( $f ) { echo "File $filename created successfully.\n"; }
      else { ProvideTestFailedMessage("Unable to create file $filename."); }
      fclose($f);
   }
   $f = fopen($RotationMonitoringFile,'r');
   if( $f ) { echo "File $filename successfully opened for reading.\n"; }
   else { ProvideTestFailedMessage("Unable to open file $filename for reading."); }
   $previousContent = file_get_contents($RotationMonitoringFile);
   file_put_contents($RotationMonitoringFile,'X');
   $newContent = file_get_contents($RotationMonitoringFile);
   file_put_contents($RotationMonitoringFile,$previousContent);
   if( $newContent == 'X' ) { echo "File $filename written to successfully.\n"; }
   else { ProvideTestFailedMessage("Unable to write to file $filename."); }
   echo "\nAll good :)</pre>";
   exit;
} # function DoFileCreateUpdateTests()

function ProvideTestFailedMessage($message)
{
   echo "$message\n\nThe file may need 777 permissions (first created, if not already existing).</pre>";
   exit;
} # function ProvideTestFailedMessage()
?>

Copy the source code and save it as a file named eir.php ("eir" for "Easiest Image Rotator," the name of the software). Upload eir.php into the subdirectory where your images are or will be.

The source code file may be named something other than eir.php so long as it has the .php file name extension. File name eir.php is assumed in this article.

Make a note of the eir.php file's URL. (In the examples, we'll assume http://example.com/images/eir.php is its URL.) You'll need the URL to publish the images.

Publishing the Images

Easiest Image Rotator selects from among all the web page-publishable images in the subdirectory where the PHP script is installed. Web page-publishable images are image files with .jpg, .jpeg, .png, or .gif file name extensions.

For some web pages, it's imperative that the images are all the same size. That would be true, for example, when the available space is exact.

The images delivered by Easiest Image Rotator are, however, responsive to available width. If the width shrinks, the image becomes smaller. If the width expands, the image becomes larger, but never larger than it's natural size to prevent pixelation.

Images can be published in web pages with JavaScript or with PHP. Either way, one line of code does it.

These two examples publish images with random selection. Afterward, I'll show you how to force rotation instead of random.

The JavaScript code example:

<script src="http://example.com/images/eir.php?js=1"></script>

Replace http://example.com/images/eir.php with the URL of your installation of the eir.php script. The ?js=1 appended to the URL is required so Easiest Image Rotator knows to return the selected image code as JavaScript.

For WordPress, JavaScript code can be inserted into text widgets and also into posts/pages when the "Text" editing tab is used instead of "Visual".

The PHP code example:

<?php echo(file_get_contents("http://example.com/images/eir.php")) ?>

Replace http://example.com/images/eir.php with the URL of your installation of the eir.php script.

For WordPress, PHP code can be used in the WordPress templates or inserted into posts/pages with the Insert PHP plugin.

Forcing Rotation Selection Instead of Random Selection

The above JavaScript and PHP code publish random-selected images. Easiest Image Rotator gets a list of available images and randomly selects one.

Because it selects from the entire list without knowing what the previous selection was, it's possible that it will select the same image two or more times in a row. (The more images there are to select from, the less often the same image should be selected twice in a row.)

To force rotation through all the available images, instead of random selection, Easiest Image Rotator needs to know what the previous selection was.

That means Easiest Image Rotator needs to keep a file with information about the last image selected.

Testing file access —

To see whether or not Easiest Image Rotator can maintain a file on your server without your intervention, type its URL into your browser with ?test=yes appended. Example:

http://example.com/images/eir.php?test=yes

The test will tell you whether or not Easiest Image Rotator succeeds in creating and updating the file required for rotation selection:

  • If it tells you all is good, you're good to go.

  • Otherwise, you'll need to:

    1. Put a file named last-rotated.txt into the subdirectory where the images are.
    2. Give the last-rotated.txt file 777 permissions.

    Then run the test URL again to verify Easiest Image Rotator can update the file.

Now, with Easiest Image Rotator able to access the file required for rotated selection let's publish images that way.

Publishing rotated images —

To publish images rotated among those available, Easiest Image Rotator needs to be told to do rotation. It's done with the rotate=1 parameter in the JavaScript or PHP code.

Here is the JavaScript code with the rotate=1 parameter included:

<script src="http://example.com/images/eir.php?js=1&rotate=1"></script>

As before, replace http://example.com/images/eir.php with the URL of your installation of the eir.php script. Also as before, the ?js=1 appended to the URL is required. To specify rotation, notice &rotate=1 appended to the URL. That delivers the rotation instruction to Easiest Image Rotator.

The PHP code example with the rotate=1 parameter included:

<?php echo(file_get_contents("http://example.com/images/eir.php?rotate=1")) ?>

Replace http://example.com/images/eir.php with the URL of your installation of the eir.php script. To deliver the rotation instruction to Easiest Image Rotator, append ?rotate=1 to the URL as shown.

After you play with it a bit, you'll realize Easiest Image Rotator really is ultra, ultra easy.

It's easy to install. And it's easy to maintain — changing the images files in the subdirectory will automatically change the images selected for publication.

And the images are responsive to available width.

(This article first appeared in Possibilities newsletter.)

Will Bontrager

Was this article helpful to you?
(anonymous form)

Support This Website

Some of our support is from people like you who see the value of all that's offered for FREE at this website.

"Yes, let me contribute."

Amount (USD):

Tap to Choose
Contribution
Method

All information in WillMaster Library articles is presented AS-IS.

We only suggest and recommend what we believe is of value. As remuneration for the time and research involved to provide quality links, we generally use affiliate links when we can. Whenever we link to something not our own, you should assume they are affiliate links or that we benefit in some way.

How Can We Help You? balloons
How Can We Help You?
bullet Custom Programming
bullet Ready-Made Software
bullet Technical Support
bullet Possibilities Newsletter
bullet Website "How-To" Info
bullet Useful Information List

© 1998-2001 William and Mari Bontrager
© 2001-2011 Bontrager Connection, LLC
© 2011-2024 Will Bontrager Software LLC