2

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!

asdf
  • 460
  • 1
  • 10
  • 31
  • you haven't done anything wrong, do you know what the `.` and `..` are ? –  Jun 05 '14 at 04:08
  • Possible duplicate: http://stackoverflow.com/questions/7132399/why-is-it-whenever-i-use-scandir-i-receive-periods-at-the-beginning-of-the-arr – Mark Miller Jun 05 '14 at 04:13

3 Answers3

2

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

<?php
$ffs = array_diff(scandir($dir), array('..', '.'));
?>
Ali Gajani
  • 14,762
  • 12
  • 59
  • 100
2

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.

l'L'l
  • 44,951
  • 10
  • 95
  • 146
0

This should do it!

<?php

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

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

?>
Brobin
  • 3,241
  • 2
  • 19
  • 35