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

后端 未结 7 858
终归单人心
终归单人心 2021-01-01 17:01

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



        
相关标签:
7条回答
  • 2021-01-01 17:35

    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");
    }
    
    0 讨论(0)
  • 2021-01-01 17:40
    <?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 />");
    }
    ?>
    
    0 讨论(0)
  • 2021-01-01 17:42

    You can use this beautiful script:

    http://halgatewood.com/free-php-list-files-in-a-directory-script/

    0 讨论(0)
  • 2021-01-01 17:44
    <?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>
    
    0 讨论(0)
  • 2021-01-01 17:47

    Using glob and sort it should work.

    0 讨论(0)
  • 2021-01-01 17:57

    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.

    0 讨论(0)
提交回复
热议问题