Skip to content

Instantly share code, notes, and snippets.

@irazasyed
Last active December 9, 2015 22:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save irazasyed/4340750 to your computer and use it in GitHub Desktop.
Save irazasyed/4340750 to your computer and use it in GitHub Desktop.
PHP: getRandomImg from any directory! (Supports JPG/JPEG & PNG)
<?php
/**
* Picks one random jpg/jpeg/png format image from the specified directory.
* @param string $dir Images directory path.
* @param boolean $realPath True to return real path of the image.
* @return string Path to one random image.
*/
function getRandomImg ( $dir, $realPath = false ) {
$dir = rtrim($dir, '/'); // Just in case if there is any trailing slash.
$images = glob($dir . '/*.{jpg,jpeg,png}', GLOB_BRACE);
shuffle($images);
$image = $images[array_rand($images)];
return ($realPath) ? realpath($image) : $image;
}
/**
* Usage:
*
* Pass the directory path from which the random image should be selected.
*
* Example:
* <?php
* $image = getRandomImg('./uploads/images');
*
* echo '<img src="'. $image .'" />';
* ?>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment