Products
Services
Contact Us

Scripts: Php :: Php file system >> Library Article #3

Developer's Section

Get all files from a folder
By: Erobo Team Member

Hire a Developer for Related Work / Installation | $55 hr
Rating:  | Rate It:   
Average Votes: (2739)
Favorites:

Learn to get all files from a single folder in your server using PHP.

In this tutorial we will demonstrate how to get all files from a folder in your server. Then we will show you how to access the content of each file.

Step 1: Create Get all files from a folder in PHP
We first need to create a method that can pull out all the files from a folder so that we can edit each of them.

 Code Snippet 1

<? 
  //Function get all files from a directory
  function dirList ($directory) 
 {

    // create an array to hold directory list
    $results = array();

    // create a handler for the directory
    $handler = opendir($directory);

    // keep going until all files in directory have been read
    while ($file = readdir($handler)) {

        // if $file isn't this directory or its parent, 
        // add it to the results array
        if ($file != '.' && $file != '..')
            $results[] = $file;
    }

    // tidy up: close the handler
    closedir($handler);

    // done!
    return $results;

}  
?>


Step 2: Create a file processor
We need to create a script that uses the dirList method to get all the files from a folder. Then we will use two simple loops to edit each and every line of each of the files in that folder.

 Code Snippet 2

<?
 //myresult contains an array with all
 //files from a directory
 $myresult = dirList("thisdirectory/");
 
 
 for($i = 0; $i < count($myresult); $i++)
 {
     //create a an array to hold the contents of the file being edited

     $arr = file("http://www.yoursite.com/thisdirectoy/" . $myresult[$i] );

     $file = 'thisdirectory/' . $myresult[$i];
     //open current file to be edited
     $fh = fopen($file, 'w') or die("can't open file");

     for($z = 0; $z < count($arr); $z++)
     {
        //get a line from the current file being edited
        $stringData = $arr[$z];
        
        //add something to the line
        $stringData = $stringData . " add this to this line";
         
        fwrite($fh, $stringData);
     }

 fclose($fh);

 }
 
?>


See other Scripts in Php file system

Submit Your Scripts:


System Message:
  • Your PHP script has been sent. Please allow 48 hours for processing.


If you would like to have your PHP scripts published in this section please fill out
the form below:
*Your Name or Username:
Home Town:
*Email:
*Description and Code:
*Enter Code shown
to the right:

[ Refresh Image ]