Jump to content

Directory file and folder count


pein87

Recommended Posts

Hello, I was trying to help someone out on another site and found that I needed some help myself. I wrote a function that gets the count of both files and folders in a directory. The problem is that it doesn't get sub directories and their file count. While it is doing that I'd like it to get the file size of each file as it goes through the loop. Does anyone know how to do this or how I could implement it so I get the desired effect?

 

Here is what I got so far. It works but it doesn't do sub folders and their files and sub folders.

 

<?php
function fileCount($p,$s = "/")
{
    $pL = strlen($p); // length of the path string
    $pE = substr($p,$pL - 1, $pL);// holds if the end value is / or not.
    $dC = 0; // used to hold the count of folders
    $fC = 0; // holds the count of files.
    $h = '';
    $f = '';
    if($pE == $s)
    {
        // person added delimter for path lets get to work without adding the delimter in code
        $h = opendir($p);
        while(($f = readdir($h)) !== false)
        {
            //loop through the directory and create counters
            if($f != "." && $f != "..")
            {
                // make sure the value of $f does not equal . or .., since it doesnt we check if each value is a file or folder
                if(is_dir($p . $f))
                {
                    $dC++;
                }
                else if(is_file($p . $f))
                {
                    $fC++;
                }
                
            }
        }
        
        $l = array($dC,$fC);
        return $l;
    }
    else
    {
        // person added delimter for path lets get to work without adding the delimter in code
        $h = opendir($p . $s);
        while(($f = readdir($h)) !== false)
        {
            //loop through the directory and create counters
            if($f != "." && $f != "..")
            {
                // make sure the value of $f does not equal . or .., since it doesnt we check if each value is a file or folder
                if(is_dir($p . $s . $f))
                {
                    $dC++;
                }
                else if(is_file($p . $s . $f))
                {
                    $fC++;
                }
                
            }
        }
        
        $l = array($dC,$fC);
        return $l;
    }
} 

 

MOD EDIT: code tags added.

Link to comment
https://forums.phpfreaks.com/topic/244885-directory-file-and-folder-count/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.