featured computer 850

PHP – Generate a Random Advertisement or Image


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.

function myGetRandom($strDirPath) {

    // 2011-09 http://kimbriggs.com/computers/
    // Function creates a random ad 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 last lines are commented.

    // 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;
    $strRandFile = $arrFileNames[array_rand($arrFileNames)];
    // Use the line below for Ad Text
    // Use the line below for an Image
    //echo "<img src=\"".$strDirPath."/".$strRandFile."\" />";
  • Create a set of directories that let you know what size ads are in them, e.g., ads-125×125, ads-160xX, ads-728×90, etc.
  • Put all your ad codes in the appropriate size-related directory. There should be only one ad code in each text file.
  • 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.
<title>My Title</title>
<?php require_once("lib.inc") ?>
  • To use within a PHP page, assign the directory variable and call the funtion.
<!--Get Random Ad-->
<?php $strDirPath="/inc/ads-160xX"; 
myGetRandom($strDirPath); ?>

References: The part about getting a directory listing is from the PHP Manual.

Similar Posts