Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to list files in a directory without listing subdirectories

Tags:

file

php

list

This is the starting portion of my code to list files in a directory:

$files = scandir($dir); 
$array = array(); 
foreach($files as $file)
{
    if($file != '.' && $file != '..' && !is_dir($file)){
          ....

I'm trying to list all files in a directory without listing subfolders. The code is working, but showing both files and folders. I added !is_dir($file) as you see in my code above, but the results are still the same.

like image 527
Pinkie Avatar asked Oct 07 '11 08:10

Pinkie


1 Answers

Use the DIRECTORY_SEPARATOR constant to append the file to its directory path too.

    function getFileNames($directoryPath) {
        $fileNames = [];
        $contents = scandir($directoryPath);

        foreach($contents as $content) {
            if(is_file($directoryPath . DIRECTORY_SEPARATOR . $content)) {
                array_push($fileNames, $content);
            }
        }

        return $fileNames;
    }
like image 190
rplaurindo Avatar answered Nov 02 '22 05:11

rplaurindo