Summary

Below is a function that can generate a random advertisement within you HTML page. I have made it modular, so that it can be reused for different geometries within the page. Below are very brief instructions on how to use it.

<?php function myGetRandom($strDirPath) {     //     // PHP AD OR IMAGE ROTATOR SCRIPT     //     // 2011-09 http://kimbriggs.com/computers/     //     // Function creates a random advertisement from a directory of text files,     // where each text file contains the HTML for 1 ad. ... OR ...     // Displays a random image from a directory of images.     //     // Parameters:     // strDirPath = The directory containing ad code files or images,     // relative to server root.     //     // Returns:     // HTML Code for a random advertisement or Image.     //     // Assumptions:     // Ad code is in a protected "inc" type directory.     // Image files are in a directory readable by the webserver.     //     // TO CHANGE VERSIONS: Switch which of the last two lines are commented out.     //     // Make relative path understood by the server.     $strDocRoot = $_SERVER['DOCUMENT_ROOT'];     $strTruePath = $strDocRoot.$strDirPath;     // Create an array of file names. Pick a random one.     if ($handle = opendir($strTruePath)) {       while (false !== ($strFile = readdir($handle))) {           if ($strFile != "." && $strFile != "..") {             $arrFileNames[] = $strFile;           }       }       closedir($handle);     }     $strRandFile = $arrFileNames[array_rand($arrFileNames)];     // Use the line below for Ad Text     include($strTruePath."/".$strRandFile);     // Use the line below for an Image     //echo "<img src=\"".$strDirPath."/".$strRandFile."\" />"; } ?>

  1. Create a set of directories that let you know what size ads are in them, e.g., ads-125x125, ads-160xX, ads-728x90, etc.
  2. Put all your ad codes in the appropriate size-related directory. There should be only one ad code in each text file.
  3. Include a file that contains the above PHP code in the head section. Mine is in a file called "lib.inc" within the main include directory, specified by "include_path" in my php.ini file.

    <head> <title>My Title</title> <?php require_once("lib.inc") ?> </head>

  4. To use within a PHP page, assign the directory variable and call the funtion:

    <!--Get Random Ad--> <p><?php $strDirPath="/inc/ads-160xX"; myGetRandom($strDirPath); ?></p>

References: I found the solution to dealing with different absolute paths on my hosting account versus home server here. The part about getting a directory listing is from the PHP Manual.