How to get a directory listing

Three functions to determine if a file or directory exists

Function Description
is_file($path) Returns TRUE if $path exists and is a file.
is_dir($path) Returns TRUE if $path exists and is a directory.
file_exists($path) Returns TRUE if $path exists and is either a file or a directory.

A function to get the current directory

Function Description
getcwd() Returns a string that specifies the current working directory.

A constant that contains the correct path separator

Constant Description
DIRECTORY_SEPARATOR A backslash on Windows servers or a forward slash on Mac OS and Linux servers.

A function to get a directory listing

Function Description
scandir($path) Returns an array containing a list of the files and directories in $path if $path is a valid directory name. Otherwise, it returns FALSE.

Display a directory listing

      $path = getcwd(); 
      $items = scandir($path); 
      echo("<p>Contents of $path</p>");
      echo("<ul>");
      foreach ($items as $item) {
        echo("<li>$item</li>");
      } 
      echo("</ul>");
      

Display the files from a directory listing

      $path = getcwd(); 
      $items = scandir($path); 
      $files = array(); 
      foreach ($items as $item) { 
        $item_path = $path . DIRECTORY_SEPARATOR . $item; 
        if (is_file($item_path)) { 
          $files[] = $item;
        }
      } 
      echo("<p>Files in $path</p>");
      echo("<ul>");
      foreach ($files as $file) { 
        echo("<li>$item</li>"); 
      } 
      echo("</ul>");
      

Back