Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the file name under a folder?

Tags:

file

php

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?

like image 475
Charles Yeung Avatar asked Jun 04 '11 01:06

Charles Yeung


People also ask

Can I copy the names of files in a folder?

Press "Ctrl-A" and then "Ctrl-C" to copy the list of file names to your clipboard.

Why can't I see the names of my files?

Go to Options, and select the Change folder and search options. Select the View tab. In Advanced settings, select Show hidden files, folders, and drives. Select Ok.


2 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;
  }
}
?>
like image 192
Lawrence Cherone Avatar answered Sep 20 '22 19:09

Lawrence Cherone


Try this:

if ($handle = opendir('.')) {
    $files=array();
    while (false !== ($file = readdir($handle))) {
        if(is_file($file)){
            $files[]=$file;
        }
    }
    closedir($handle);
}
like image 29
AJ. Avatar answered Sep 20 '22 19:09

AJ.