简体   繁体   中英

How to count files inside a folder using PHP?

The following code counts the number of files inside a folder.

<?php
function folderlist(){
  $directoryist = array();
$startdir = './';
//get all image files with a .jpg extension.
  $ignoredDirectory[] = '.';
  $ignoredDirectory[] = '..';
   if (is_dir($startdir)){
       if ($dh = opendir($startdir)){
           while (($folder = readdir($dh)) !== false){
               if (!(array_search($folder,$ignoredDirectory) > -1)){
                 if (filetype($startdir . $folder) == "dir"){
                       $directorylist[$startdir . $folder]['name'] = $folder;
                       $directorylist[$startdir . $folder]['path'] = $startdir;
                   }
               }
           }
           closedir($dh);
       }
   }
return($directorylist);
}


$folders = folderlist();

$total_files = 0;
foreach ($folders as $folder){
    $path = $folder['path'];
    $name = $folder['name'];
    $count = iterator_count(new DirectoryIterator($path . $name));
    $total_files += $count;

    echo '<li>';
    echo '<a href="' .$path .'index.php?album=' .$name . '" class="style1">';
    echo '<strong>' . $name . '</strong>';
    echo ' (' . $count . ' files found)';
    echo '</a>';
    echo '</li>';
}
  echo "Total Files:". $total_files;
?>

However for some reason the count is off by 2. I have a folder with 13 files but this code returns count as 15. For an empty folder, this returns a count of 2.

Can someone point to me the issue with the above snippet?

I'm doing it with DirectoryIterator

$files_in_directory = new DirectoryIterator($path_to_folder);
$c = 0;

foreach($files_in_directory as $file)
{
    // We want only files
    if($file->isDot()) continue;
    if($file->isDir()) continue;
    $c++;
}

var_dump($c);

For use as function :

function folderlist($directories = array(), $extensions = array())
{
    if(empty($directories))
        return false;

    $result      = array();
    $total_count = 0;
    foreach($directories as $directory)
    {
        $files_in_directory = new DirectoryIterator($directory);
        $c                  = 0;

        foreach($files_in_directory as $file)
        {
            // We want only files
            if($file->isDot()) continue;
            if($file->isDir()) continue;

            // This is for php < 5.3.6
            $file_extension = pathinfo($file->getFilename(), PATHINFO_EXTENSION);

            // If you have php >= 5.3.6 you can use following instead
            // $file_extension = $fileinfo->getExtension()

            if(in_array($file_extension, $extensions)){
                $c++;
                $result['directories'][$directory]['files'][$c]['name'] = $file->getFilename();
                $result['directories'][$directory]['files'][$c]['path'] = $file->getPath();
                $result['directories'][$directory]['count']             = $c;
            }     
        }
        $total_count += $c;    
    }

    $result['total_count'] = $total_count;

    return $result;    

}

Displaying results based on GET superglobal:

if(isset($_GET['album']) && !empty($_GET['album']) && !isset($_GET['listfiles']))
    {
        // We are in directory view mode
        $album = $_GET['album'];

        // View all directories and their file count for specified album
        $view_directory = folderlist(array($album), array('jpeg', 'jpg', 'log'));

        // Loop the folders and display them with file count
        foreach ($view_directory['directories'] as $folder_name => $folder_files){

            $count = $folder_files['count'];
            echo '<li>';
            echo '<a href="files.php?album=' . $folder_name . '&listfiles=1" class="style1">';
            echo '<strong>' . basename($folder_name) . '</strong>';
            echo ' (' . $count . ' files found)';
            echo '</a>';
            echo '</li>';  

        }

        echo "Total Files:". $get_dir_info['total_count'];   

    }
    elseif(isset($_GET['album'], $_GET['listfiles']) && !empty($_GET['album']))
    {
        // We are in file view mode for folder
        $album = $_GET['album'];

        // View all files in directory
        $view_files = folderlist(array($album), array('jpeg', 'jpg', 'log'));   

        echo 'Showing folder content of: <b>'.basename($album).'</b>';
        foreach($view_files['directories'][$album]['files'] as $file)
        {     

            $path = $file['path'];
            $name = $file['name'];

            echo '<li>';
            echo '<a href="files.php?file=' . $name . '&path=' . $path . '" class="style1">';
            echo '<strong>' . $name . '</strong>';
            echo '</a>';
            echo '</li>';   
        } 
    }

This line is still returning the '.' and '..' vars.

if (!(array_search($folder,$ignoredDirectory) > -1))

see: http://php.net/manual/en/language.types.boolean.php

Try

if (!array_search($folder,$ignoredDirectory))

EDIT:

Also change this:

$ignoredDirectory[] = '.';
$ignoredDirectory[] = '..';

to

$ignoredDirectory = array( '.', '..' );

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