How can I list all files in a directory sorted alphabetically using PHP?

46,063

Solution 1

The manual clearly says that:

readdir
Returns the filename of the next file from the directory. The filenames are returned in the order in which they are stored by the filesystem.

What you can do is store the files in an array, sort it and then print it's contents as:

$files = array();
$dir = opendir('.'); // open the cwd..also do an err check.
while(false != ($file = readdir($dir))) {
        if(($file != ".") and ($file != "..") and ($file != "index.php")) {
                $files[] = $file; // put in array.
        }   
}

natsort($files); // sort.

// print.
foreach($files as $file) {
        echo("<a href='$file'>$file</a> <br />\n");
}

Solution 2

<?php
function getFiles(){
    $files=array();
    if($dir=opendir('.')){
        while($file=readdir($dir)){
            if($file!='.' && $file!='..' && $file!=basename(__FILE__)){
                $files[]=$file;
            }   
        }
        closedir($dir);
    }
    natsort($files); //sort
    return $files;
}
?>

<html>
<head>
</head>
<body>

<h1> List of files </h1>

<ul class="dir">
    <? foreach(getFiles() as $file)
        echo "<li name='$file'><a href='$file'>$file</a></li>";
    ?>
</ul>

</body>
</html>

Solution 3

You could put all the directory names inside an array like:

$array[] = $file; 

After that you can sort the array with:

sort($array); 

And then print the links with that content.

I hope this help.

Solution 4

<?php
$dirname = ".";
$dir = opendir($dirname);

while(false != ($file = readdir($dir)))
{
if(($file != ".") and ($file != "..") and ($file != "index.php"))
{
  $list[] = $file;
}
}

sort($list);

foreach($list as $item) {
echo("<a href='$item'>$item</a> <br />");
}
?>

Solution 5

Using glob and sort it should work.

Share:
46,063
David B
Author by

David B

Updated on July 09, 2022

Comments

  • David B
    David B almost 2 years

    I'm using the following PHP code to list all files and folders under the current directory:

    <?php
        $dirname = ".";
        $dir = opendir($dirname);
    
        while(false != ($file = readdir($dir)))
            {
              if(($file != ".") and ($file != "..") and ($file != "index.php"))
                 {
                  echo("<a href='$file'>$file</a> <br />");
            }
        }
    ?>
    

    The problem is list is not ordered alphabetically (perhaps it's sorted by creation date? I'm not sure).

    How can I make sure it's sorted alphabetically?

  • David B
    David B over 13 years
    This is the first time I use PHP. I only need it to list some stuff I uploaded to my apache. Could you please show me how to store the files in an array and sort it?
  • Bobby Jack
    Bobby Jack over 13 years
    +1 for natsort() might even want to think about natcasesort()
  • Pekka
    Pekka over 13 years
    @David you could use $files = glob("/your/path/*");
  • Bobby Jack
    Bobby Jack over 13 years
    @Pekka: that won't return hidden files. Other than the obvious 'navigation pseudo files', the question doesn't suggest whether hidden files are needed, so it's probably safer to assume they are until told otherwise.
  • Jan.
    Jan. over 13 years
    @David B: By the way: Filenames can contain HTML-Metacharacters. So one should escape them before outputting. Also, you want to check the files being uploaded for validity. Not that one can upload php files or so, which will be executed then..
  • Bobby Jack
    Bobby Jack over 13 years
    Jan, What's the reason to not use openddir/readdir? Neither is deprecated.
  • Pekka
    Pekka over 13 years
    @Bobby good point. However this seems to be possible to circumvent: php.net/manual/en/function.glob.php#68869
  • codaddict
    codaddict over 13 years
    @Pekka: Just verified that glob gives sorted output. +1 to you.
  • Jan.
    Jan. over 13 years
    because OOP is the way to go. Also the Iterator-classes have a lot of features implemented build-into php, which you would have to code manually when you use opendir(). So I believe this would also be better for performance or security reasons.
  • Pekka
    Pekka over 13 years
    @cod it does? That comes as a surprise! :) I rather meant glob() to fetch the data needed for your sorting suggestion. (I would still sort it explicitly, the behaviour could vary across systems.)
  • codaddict
    codaddict over 13 years
    @Pekka: glob uses an option GLOB_NOSORT which tells it to return unsorted output. So looks like it's default behavior is to give sorted output.
  • Mark Baker
    Mark Baker over 13 years
    no need to sort() if you use glob() because it sorts alphabetically by default
  • David B
    David B over 13 years
    For some reason, this doesn't print anything. I added $dir= "."; at the beginning (it's missing) but still nothing.
  • codaddict
    codaddict over 13 years
    @David: you need to use a opendir before you do a readdir
  • David B
    David B over 13 years
    @codaddict yeah, I just got it. Thanks!
  • Vitim.us
    Vitim.us over 11 years
    I'm a php noob, but Shouldn't you do closedir($dir); ?
  • CommaToast
    CommaToast over 9 years
    Yes but what is "the order in which they are stored by the filesystem"? Does this differ between file systems? How can you have your script check what it is, since I mean, it might be running on who knows what OS?
  • mickmackusa
    mickmackusa about 4 years
    Link-only answers are vulnerable to breakage. All answers are expected to contain their advice as static text. Adding a link is supportive, but there needs to be more.