Retrieve and output certain files within a directory
I thought I'd kick start this forum by posting a PHP code I put together yesterday to allow me to retrieve all files within a directory, limited by file types (ie: images only). I needed it to dynamically populate a JavaScript slideshow with all images from a directory without maually specifying each image. Here it is:
PHP Code:
//This function retrieves all files within a directory (non recursive) and outputs them onto the page //You can limit the type of files to retrieve, such as images only, as dictated by the file's extension
function getfiles($dirname=".") { $pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions $files = array(); if($handle = opendir($dirname)) { while(false !== ($file = readdir($handle))){ if(eregi($pattern, $file)) //if this file is a valid image echo "$file <br />"; }
closedir($handle); } return($files); } //EXAMPLE USAGE: getfiles(); //List all image files within the directory the PHP script is in getfiles("/home/myserver/public_html/george"); //List all image files within a specific directory on the server
Hi Error 404:
You read my mind. that Using regular expressions to properly detect a valid image format was one of the things I knew I had to add. Thanks for the modification.
__________________
- George
- JavaScript Kit- JavaScript tutorials and 400+ scripts!
- JavaScript Reference- JavaScript reference you can relate to.
//This function retrieves all files within a directory (non recursive) and outputs them onto the page
//You can limit the type of files to retrieve, such as images only, as dictated by the file's extension
function getfiles($dirname=".") {
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
$files = array();
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file) || is_dir($file)) //if this file is a valid image or folder
echo "$file <br />";
}
closedir($handle);
}
return($files);
}
//EXAMPLE USAGE:
getfiles(); //List all image files within the directory the PHP script is in
getfiles("/home/myserver/public_html/george"); //List all image files within a specific directory on the server