Life of a web developer

November 23, 2010

Tutorial: randomImage() – A “new” way to select random images directly from the directory

Filed under: PHP, Tutorials — Tags: , , , — Ole Aass @ 8:55 pm

So, I stumbled across a very handy php function today called glob().

The glob() function returns an array of filenames or directories matching a specified pattern.
This function returns an array of files/directories, or FALSE on failure.

So I figured this would be great for showing stuff like random ads etc, and had to give it a closer look. The following function is what I used to try it out

/**
 * Select a random image from a directory
 * 
 * @param string $path The full directory path to where the images are located
 * @param bool $removePath If this is set to true, only the filename will be returned. (Default: false)
 * @param string $pattern The pattern it will use to filter out what files to grab. (Default: * (will select all filename))
 * @param string $validExtension All valid extensions separated by comma (Default: gif,jpg,png)
 */
function randomImage($path, $removePath = false, $pattern = '*', $validExtensions = 'gif,jpg,png') {

	// Place all image files in an array
	$images = glob($path.$pattern.'.{'.$validExtensions.'}', GLOB_BRACE);
	
	// Check if the result turned up empty
	if (!$images) {
		return false;
	}
	
	// Pick a random image from the array
	return ($removePath) ? str_replace($path, '', $images[array_rand($images)]) : $images[array_rand($images)];
}

Usage:

print_r(randomImage('images/', false));
Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: