i want to write a page that will traverse a specified directory.... and get all the files in that directory...
in my case the directory will only contain images and dis
<?php
//define directory
$dir = "images/";
//open directory
if ($opendir = opendir($dir)){
//read directory
while(($file = readdir($opendir))!= FALSE ){
if($file!="." && $file!= ".."){
echo "<img src='$dir/$file' width='80' height='90'><br />";
}
}
}
?>
source: phpacademy.org
You'll want to use the scandir function to walk the list of files in the directory.
I use something along the lines of:
if ($dir = dir('images'))
{
while(false !== ($file = $dir->read()))
{
if (!is_dir($file) && $file !== '.' && $file !== '..' && (substr($file, -3) === 'jpg' || substr($file, -3) === 'png' || substr($file, -3) === 'gif'))
{
// do stuff with the images
}
}
}
else { echo "Could not open directory"; }
You could also try the glob function:
$path = '/your/path/';
$pattern = '*.{gif,jpg,jpeg,png}';
$images = glob($path . $pattern, GLOB_BRACE);
print_r($images);
I would start off by creating a recursive function:
function recurseDir ($dir) {
// open the provided directory
if ($handle = opendir($_SERVER['DOCUMENT_ROOT'].$dir)) {
// we dont want the directory we are in or the parent directory
if ($entry !== "." && $entry !== "..") {
// recursively call the function, if we find a directory
if (is_dir($_SERVER['DOCUMENT_ROOT'].$dir.$entry)) {
recurseDir($dir.$entry);
}
else {
// else we dont find a directory, in which case we have a file
// now we can output anything we want here for each file
// in your case we want to output all the images with the path under it
echo "<img src='".$dir.$entry."'>";
echo "<div><a href='".$dir.$entry."'>".$dir.$entry."</a></div>";
}
}
}
}
The $dir param needs to be in the following format: "/path/" or "/path/to/files/"
Basically, just don't include the server root, because i have already done that below using $_SERVER['DOCUMENT_ROOT'].
So, in the end just call the recurseDir function we just made in your code once, and it will traverse any sub folders and output the image with the link under it.
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file\n";
}
}
closedir($handle);
}
use readdir