PhP: Read Filenames in a Directory

Currently I’m working on thousands of essays for my quantitative studies. Yes 1315 .txt files in one folder, all waiting to be analysed by XIP. In the pilot study I worked with 89 .txts which was OK to do some manual labour work but having thousands made me to put my software engineering hat and get some help from PhP.

I wanted to keep record of these codes for the sake of future myself who might need to go back again. And I thought these records can be useful for other people too so I’ll blog every bit. Well this simple tutorial will give you how to:

  1. Open Directory
  2. Read all filenames within the directory
  3. And put all filenames in an array

<?php

$dir = “…”;  //give the directory path you want to open
$scanned_dir = array_diff(scandir($dir), array(‘..’, ‘.’));  //If you dont do this when you read the directory and list the file names you’ll see . and .. listed as filenames; so this line handles the problem and removes . and ..
$dirhandle = opendir($scanned_dir); //open the directory

if ($dirhandle) { //if directory name exists

//Loop through the directory
while (false !== ($filename = readdir($dirhandle))) {

$files[] = $filename; //add each file name to files array

}

closedir($handle); //close the directory
}

sort($files); //sorts alphabetically
print_r($files); //in case you want to print them

?>

Leave a Reply

Your email address will not be published. Required fields are marked *

For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

I agree to these terms.

One thought on “PhP: Read Filenames in a Directory