Select Page

random-php-computer-programmerA goal that we have for every client’s website is to keep the content as fresh as possible.? Many site builds aren’t ready-made for consistently changing content; often people want a set-it and forget-it brochure site.

Even on static sites, it is possible to create some variety to keep users and search engines interested.? If you have new/different content each time a search spider visits your site, they are more likely to visit and re-index your site often.

One of the many methods we’ve used to automate this “fresh” content is to display a random on-page image.? If you have 3 images that showcase your products/services, but only have the space to show one on your homepage, why not rotate between the 3 images randomly?? This gives the page variety each time it is reloaded or re-visited.

The PHP code to accomplish this is quite simple, and can be implemented by people with very little PHP experience.? Firstly, you will need a file that contains an array of possible images, and related data:

$imageArray = array(
     1 => array("address" => "/images/image1.jpg", "alt_text" => "Image 1"),
     2 => array("address" => "/images/image2.jpg", "alt_text" => "Image 2"),
     3 => array("address" => "/images/image1.jpg", "alt_text" => "Image 3"),

Save this array to it’s own file, and upload it to the appropriate place for includes on your web server.

Now we need the code that goes on the desired display page, which will randomly select one array item, and display the entry as an image:

     //Include the file which contains the Image array
     include $_SERVER['DOCUMENT_ROOT'] . "/includes/imageArray.php";

     //This selects the index number of one random array entry.
     $randomImageNumber = array_rand($imageArray, 1);

     //This prints to the screen an HTML image tag with attributes pulled
     //from the randomly selected array entry.
     echo "<img src='" . $imageArray[$randomImageNumber]['address'] . "'
     alt='" . imageArray[$randomImageNumber]['alt_text'] . "' />";

Now all you need to do is add any styling required to the image tag, make sure you’ve uploaded the images, and you should have a randomly rotating image every time your page is reloaded.? By getting a little bit creative, the array and code can be easily modified so that the images are each hyperlinked to a unique URL, and more than one image can be shown at a time from the same array – look for these advanced technique in a future post!

What techniques have you used in the past to create automated fresh content for your website?? What other features/advancements would you like to see on this script?

  • Facebook
  • Twitter
  • StumbleUpon
  • email