PHP read directory into array
Written by Codes Tips on April 12, 2009 – 4:10 am -In this short tutorial I will show how you can read directory into array that is on the server where the script is placed. We will get the names of all the files from that directory. For doing this you should create a handler for the directory by using opendir, passing the name of the directory.
After creating a handler to that directory we should iterate through all the files of that directory, so we gone use a loop until all the files from that directory are read:
while ($file = readdir($handler)) {
//get the name of the file
}
After reading finishing the loop we should close the handler to that directory.
closedir($handler);
Code:
$directory="exampledir";
// create a handler to the directory
$dirhandler = opendir($directory);
// read all the files from directory
$nofiles=0;
while ($file = readdir($dirhandler)) {
// if $file isn't this directory or its parent
//add to the $files array
if ($file != '.' && $file != '..')
{
$nofiles++;
$files[$nofiles]=$file;
}
}
//close the handler
closedir($dirhandler);
Tags: PHP
Posted in PHP/MYSQL |
3 Comments to “PHP read directory into array”
Leave a Comment
You must be logged in to post a comment.



















April 25th, 2009 at 12:02 am
[...] were created. To do that we only need to loop through the cache folder(go here for learning how to get all the files from a folder) and delete all the files that are inside that folder. Remember to change permissions 777 to cache [...]
May 23rd, 2009 at 3:41 pm
May 23rd, 2009 at 5:02 pm
Hello Tim,
Thanks for your sharing. Please include code between
next time.