How to read files inside a directory using PHP

Sometimes when you write code you need to access the file system, navigate to a specific directory and get files inside that directory to perform some operations using the data in the files.
So to open and list files inside a directory you could use following code.
$baseDir = "D:/MyFolder/subfolder/";
$dh = opendir($baseDir);
while (($currentDir = readdir($dh)) !== false){
 if ($currentDir != '.' && $currentDir != '..'){
  $fileList = glob($baseDir.'*.xml');
 }
}
You can set the path to the directory and use opendir() to get a directory handler. Through the readdir() we can read the directory. It will return a list of file names if success or else 'false' in error.
The function glob() is used here just as an extra tip. You can use glob() to filter files using it's name. For example here I have filtered only XML files. Asteric is used to denote any name but exactly following .xml extension.
You can also use glob() as 'ma*.php' or 'manual.*' or anything like that.
This is a full function you can also use in your code.
function listFilesInDir($baseDir,$fileType) {
    $fileList = array();
    $dh = opendir($baseDir);
    while (($dir = readdir($dh)) !== false) {
        if ($dir != '.' && $dir != '..'){
            if ($fileType == null || $fileType == "") {
                array_push($fileList, $dir);
            }
            else{
                $fileList = glob($baseDir.''.$fileType);
            }
        }
    }
    return $fileList;
}
You can print and see the list like this.
$result = listFilesInDir("D:/MyFolder/subfolder/","*_e*.xml");
var_dump($result);

Comments

Popular Posts