I want to open a directory and read all the files inside and put them into an array
, so far I have:
$imagesdir = $CFG->dataroot.'/1/themeimages/';
Which gives me the path to the directory, whats the next step?
I want to open a directory and read all the files inside and put them into an array
, so far I have:
$imagesdir = $CFG->dataroot.'/1/themeimages/';
Which gives me the path to the directory, whats the next step?
A solution would be to use opendir
+ readdir
+ closedir
(quoting an example from the first page) :
$imagesdir = $CFG->dataroot.'/1/themeimages/';
if ($handle = opendir($imagesdir)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file\n";
}
}
closedir($handle);
}
Another solution would be to use the [DirectoryIterator
class ; quoting the example from]4 the __construct
page :
$imagesdir = $CFG->dataroot.'/1/themeimages/';
$dir = new DirectoryIterator($imagesdir);
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
var_dump($fileinfo->getFilename());
}
}
Of course, in each case, instead of just echoing or dumping the name of the file, you'd have to put it into an array.
This would mean initializing the array before the loop :
$list_files = array();
And, inside the loop, use something like one of those two lines, depending on which solution you choose :
$list_files[] = $file;
$list_files[] = $fileinfo->getFilename();
Just use the built in function scandir:
Returns an array of files and directories from the directory .
So you would use it like this:
$array = scandir($imagesdir);
Of course you can use DirectoryIterator too, but this is much simplier.
You can also strip dot files:
$array = array_diff(scandir($imagesdir), array('.', '..'));
For a more OO approach use the DirectoryIterator class.
$images = array();
$imagesdir = $CFG->dataroot.'/1/themeimages/';
foreach (new DirectoryIterator($imagesdir) as $file) {
if($file->isDot()) continue;
$images[] = $file;
}
here's the shortest solution if you also need a filter later on:
$imagesdir = $CFG->dataroot.'/1/themeimages/*.*';
foreach (glob($imagesdir) as $file)
array_push($files,$file);
php automatically excludes .
and ..
you can also specify your own mask if you don't need ALL files, as shown in above *.*
php also automatically creates the $files
array for you.
the last line can also be:
$files[]=$file;
Since from your tag list I assume you're using Moodle, you can simply use the:
function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true)
The function is contained in moodlelib.php.
Reading from the doc:
- Returns an array with all the filenames in * all subdirectories, relative to the given rootdir.
Please refer to the official doc for more information about the optional parameters.
Functions for reading content of files are also available in filelib.php.