Follow me on Twitter to receive updates, free scripts and ongoing announcements!

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:
Posted in PHP/MYSQL |

3 Comments to “PHP read directory into array”

  1. PHP clear cache directory | Codes Tips Says:

    [...] 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 [...]

  2. timNo Gravatar Says:
    $files = glob('directory/*');
    $files = array_filter($files, 'is_file');
  3. Codes TipsNo Gravatar Says:

    Hello Tim,
    Thanks for your sharing. Please include code between

     <pre lang="php"> an </ pre>

    next time.

Leave a Comment

You must be logged in to post a comment.


Plugintaylor.com - Plugintaylor and Affiliate Link