简体   繁体   中英

php - listing folders and files in a directory

hi there i am using the following function to list all the files and folders in a directory.

<?php

  function listFolderFiles($dir){

        $ffs = scandir($dir);

            foreach($ffs as $ff){

                echo $ff . "<br/>";

            }

    }

?>

but the problem seems to be i'm getting all the folders in the directory alright but i'm also getting a . and a .. . something like the one below.

.
..
direc
img
music
New Text Document.txt

and i am using the following function like: listFolderFiles('MyFolder');

what i want to do is get all the folders and files but not the . and the .. , what have i done wrong and how can i get what i want. thanks!

Easy way to get rid of the dots that scandir() picks up in Linux environments:

<?php
$ffs = array_diff(scandir($dir), array('..', '.'));
?>

You can use glob quite easily, which puts the filenames into an array:

print_r(glob("*.*"));

example:

// directory name
$directory = "/";

// get in directory
$files = glob($directory . "*");

$d = 0; // init dir array count
$f = 0; // init file array count

// directories and files
foreach($files as $file) { 
    if(is_dir($file)) {
        array($l['directory'][$d] =  $file);
        $d++;
    } else {
        array($l['file'][$f] = $file);
        $f++;
    }
}

print_r($l);

NOTE : scandir will also pick up hidden files such as .htaccess , etc. That is why the glob method should be considered instead, unless of course you want to show them.

This should do it!

<?php

function listFolderFiles($dir){
    $ffs = scandir($dir);
    foreach($ffs as &$ff){

        if ($ff != '.' && $ff != '..') {
            echo $ff . "<br/>";
        }
    }
}

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM