Last active
December 7, 2015 16:10
-
-
Save coccoinomane/8a0486738d20e5916eef to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- #!/usr/bin/env php --> | |
<!-- ^ Uncomment to launch from shell --> | |
<?php | |
/** | |
* Script to count the number of files in a directory and in | |
* all its subdirectories. | |
* | |
* The function returns an array with two entries: the total number | |
* of files (excluding directories) and the number of hidden files. | |
* | |
* Symbolic links will not be followed, but will be included in | |
* the file tally. | |
* | |
* Inspired by http://php.net/manual/en/function.scandir.php#110570. | |
* | |
* Created by Guido Walter Pettinari on 7/12/2015 | |
* https://gist.github.com/coccoinomane/8a0486738d20e5916eef#file-count_files-php | |
*/ | |
function count_files($dir) { | |
/* Initialise outputs */ | |
$counter = array (0,0); | |
/* Loop over each item in the directory */ | |
foreach (scandir($dir) as $value) { | |
/* Do not consider the current (.) and parent (..) dirs in the count */ | |
if (in_array($value, array(".",".."))) | |
continue; | |
/* Path of the currently considered file/directory */ | |
$path = $dir . DIRECTORY_SEPARATOR . $value; | |
/* If the current item is a directory, scan it recursively. | |
Do not follow symbolic links */ | |
if (is_dir($path) && !is_link($path)) { | |
$counter_subdir = count_files($path); | |
$counter[0] = $counter[0] + $counter_subdir[0]; | |
$counter[1] = $counter[1] + $counter_subdir[1]; | |
} | |
/* If it is a file, increase the counter */ | |
else | |
/* Visible files */ | |
if ($value[0] != '.') | |
$counter[0]++; | |
/* Hidden files */ | |
else | |
$counter[1]++; | |
} | |
return $counter; | |
} | |
# Print number of files in current directory | |
$cwd = dirname ( __FILE__ ); | |
$n_files = count_files($cwd); | |
printf ("The '%s' directory contains %d files of which %d hidden\n", $cwd, $n_files[0], $n_files[1]); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment