Scriptplayground

 Print Page | Close Window

Simple Banner Rotator

PHP powered banner rotator using the power of flat files (txt files).

This week we will build a simple banner/image rotator. We will be doing this using flat files (txt files) and a couple of file functions in php.

Here is what the banner txt file should look like, you simply just put one image/link pair per line. The "[$]" seperator is used to split apart the img/link pairs. We use this interesting seperator to ensure it is not going to be contained in the link or image reference.

google.gif[$]http://www.google.com
mkeefedesign.gif[$]http://www.mkeefedesign.com
scriptplayground.gif[$]http://www.scriptplayground.com

First off, define the variables for this project

//
// Customizable Settings for banner script
//
$banner_txt_file = 'my_banners.txt'; // Our txt file of banner references
$banner_links = true; // Show banner as just image or with link (href)

Now lets set up a function to contain all of our banner code and make it easier to call in the future.

function display_banner() {
	// use 'global' to reference our preset variables
	global $banner_txt_file, $banner_links
	
	mt_srand((double)microtime() * 100000);
	$banners = file($banner_txt_file);
	$count = count($banners);
	$random = rand(0, $count - 1);
	$banner = $banners[$random];
	$banner_parts = explode("[$]", $banner);
	$banner_img = $banner_parts[0];
	$banner_link = $banner_parts[1];

	$banner_html = "<img src=\"" . $banner_img . "\" />"; // build img tag
	if($banner_links) {
		$banner_html = "<a href=\"" . $banner_link . "\">" . $banner_html . "</a>";
	}
	return $banner_html; // return the html code
}

Now let's take a moment to explain what is happening in those last few lines. First off we define a few global variables to gain access to them in the function (scope issue).

Then we use mt_srand() to create a random seed, and ultimately allow us to pick a random banner image. Now we begin the file opening process and start reading in our banners and links. We then take these lines of link/img pairs and choose a random one to display. Finally we build our necessary html to display the banner and add the link info if $banner_links is set to true.

Note: Make sure you "chmod" the banner txt file, so it can actually be read. :)

To display a random banner, you simply place this PHP code somewhere in your file

print display_banner();

Thats it, you now have a working php banner script... next time we will create a feature packed version with MySQL, counters and all sorts of goodies.


Find this article at:
http://scriptplayground.com/tutorials/php/Simple-Banner-Rotator/