Last active
December 9, 2015 22:58
-
-
Save irazasyed/4340750 to your computer and use it in GitHub Desktop.
PHP: getRandomImg from any directory! (Supports JPG/JPEG & PNG)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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