Skip to content

Instantly share code, notes, and snippets.

@oliverbooth
Last active August 29, 2015 14:06
Show Gist options
  • Select an option

  • Save oliverbooth/028e363abd7dba52a264 to your computer and use it in GitHub Desktop.

Select an option

Save oliverbooth/028e363abd7dba52a264 to your computer and use it in GitHub Desktop.
Randomly choose a file
<?php
/**
* Randomly chooses a file from the given directory.
* @param directory Optional. The directory to search. Defaults to the current directory.
* @param ext Optional. An array of accepted file extensions to match. Defaults to standard images.
* @return A string representing the name of the file
*/
function randomFile($directory = ".", $ext = array("jpg", "jpeg", "gif", "png", "bmp")) {
// Find file matches using glob
$files = glob($directory."/*.{".implode(",",$ext)."}", GLOB_BRACE);
// Randomly choose a file
$rand = mt_rand(0, count($files) - 1);
$file = $files[$rand];
return $file;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment