Search code examples
phpfile-readfile-writing

Read list of files, and rewrite to master list


I have a directory which has say 10 .txt files. Open the directory using:

$dir_handle = @opendir($path) or die("Unable to open $path"); 

I need to be able to read the files names of the text files, and then write all those file names to a master list with a | after each file name. I also do not want the masterlist.txt to be written inside itself lol. So the masterlist.txt is what is being written to with the file names of the .txt files.


Solution

  • Loop over the directory with readdir(), and verify that each entry isn't the master list or . or ... Write it to the file with file_put_contents().

    // If master.txt already exists, delete it.
    if (file_exists('master.txt')) {
      unlink('master.txt');
    }
    
    $dir_handle = @opendir($path) or die("Unable to open $path"); 
    while ($f = readdir($dir_handle)) {
      if ($f != '.' && $f != '..' && $f != 'master.txt') {
        file_put_contents('master.txt', $f . "|", FILE_APPEND);
      }
    }
    

    If you only want .txt files, use something like:

    if (preg_match('/^(.+)\.txt$/', $f)) {
      // it's a .txt file.
    }