How to get the file name under the folder?

Suppose I have a directory:

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

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

+7
source share
7 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; } } ?> 
+13
source

Try the following:

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

scandir lists files and directories within the specified path.

+1
source

Here is the most effective Effective way based on this article :

 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 change it to get the folder path and / or required extensions, it's easy.

+1
source

Besides scandir (@miku), you can also find glob , interesting for matching wildcards.

0
source

If your text files are all that you have inside the folder, the easiest way is to use scandir, for example:

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

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

0
source
 $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); } } 

exit:

 xyz abc 2017 motopress 
0
source

All Articles