Home » Php » php – How to get the file name under a folder?

php – How to get the file name under a folder?

Posted by: admin July 12, 2020 Leave a comment

Questions:

Suppose I have a directory look like:

ABC
|_ a1.txt
|_ a2.txt
|_ a3.txt
|_ a4.txt
|_ a5.txt

How can I use PHP to get these file names to an array, limited to a specific file extension and ignoring directories?

How to&Answers:

You can use the glob() function:

Example 01:

<?php
  // read all files inside the given directory
  // limited to a specific file extension
  $files = glob("./ABC/*.txt");
?>

Example 02:

<?php
  // perform actions for each file found
  foreach (glob("./ABC/*.txt") as $filename) {
    echo "$filename size " . filesize($filename) . "\n";
  }
?>

Example 03: Using RecursiveIteratorIterator

<?php 
foreach(new RecursiveIteratorIterator( new RecursiveDirectoryIterator("../")) as $file) {
  if (strtolower(substr($file, -4)) == ".txt") {
        echo $file;
  }
}
?>

Answer:

Try this:

if ($handle = opendir('.')) {
    $files=array();
    while (false !== ($file = readdir($handle))) {
        if(is_file($file)){
            $files[]=$file;
        }
    }
    closedir($handle);
}

Answer:

scandir lists files and directories inside the specified path.

Answer:

Here is the most Efficient way based on this article‘s benchmarks:

function getAllFiles() {
    $files = array();
    $dir = opendir('/ABC/');
    while (($currentFile = readdir($dir)) !== false) {
        if (endsWith($currentFile, '.txt'))
            $files[] = $currentFile;
    }
    closedir($dir);
    return $files;
}

function endsWith($haystack, $needle) {
    return substr($haystack, -strlen($needle)) == $needle;
}

just use the getAllFiles() function, and you can even modify it to take the folder path and/or the extensions needed, it is easy.

Answer:

Aside from scandir (@miku), you might also find glob interesting for wildcard matching.

Answer:

If your text files is all that you have inside of the folder, the simplest way is to use scandir, like this:

<?php
$arr=scandir('ABC/');
?>

If you have other files, you should use glob as in Lawrence’s answer.

Answer:

$dir = "your folder url"; //give only url, it shows all folder data

if (is_dir($dir)){
    if ($dh = opendir($dir)){
        while (($file = readdir($dh)) !== false){
            if($file != '.' and $file != '..'){
                echo $file .'<br>';
            }
        }
        closedir($dh);
    }
}

output:

xyz
abc
2017
motopress