繁体   English   中英

计算目录PHP中有多少文件

[英]Count how many files in directory PHP

我正在做一个稍微新的项目。 我想知道某个目录中有多少文件。

<div id="header">
<?php 
    $dir = opendir('uploads/'); # This is the directory it will count from
    $i = 0; # Integer starts at 0 before counting

    # While false is not equal to the filedirectory
    while (false !== ($file = readdir($dir))) { 
        if (!in_array($file, array('.', '..') and !is_dir($file)) $i++;
    }

    echo "There were $i files"; # Prints out how many were in the directory
?>
</div>

这就是我到目前为止(从搜索中得到的)。 但是,它没有正确显示? 我添加了一些注释,因此请随时删除它们,它们只是为了让我尽可能地理解它。

如果您需要更多信息或觉得我描述得不够充分,请随时说明。

您可以简单地执行以下操作:

$fi = new FilesystemIterator(__DIR__, FilesystemIterator::SKIP_DOTS);
printf("There were %d Files", iterator_count($fi));

您可以像这样获取文件计数:

$directory = "/path/to/dir/";
$filecount = count(glob($directory . "*"));
echo "There were $filecount files";

如果您想要像"*.jpg"这样的"*" ,您可以将其更改为特定的文件类型,或者您可以像这样执行多个文件类型:

glob($directory . "*.{jpg,png,gif}",GLOB_BRACE)

GLOB_BRACE标志扩展 {a,b,c} 以匹配“a”、“b”或“c”

请注意glob()会跳过 Linux 隐藏文件,或名称以点开头的所有文件,即.htaccess

尝试这个。

// Directory
$directory = "/dir";

// Returns an array of files
$files = scandir($directory);

// Count the number of files and store them inside the variable..
// Removing 2 because we do not count '.' and '..'.
$num_files = count($files)-2;

你应该有 :

<div id="header">
<?php 
    // integer starts at 0 before counting
    $i = 0; 
    $dir = 'uploads/';
    if ($handle = opendir($dir)) {
        while (($file = readdir($handle)) !== false){
            if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) 
                $i++;
        }
    }
    // prints out how many were in the directory
    echo "There were $i files";
?>
</div>

我认为的最佳答案:

$num = count(glob("/exact/path/to/files/" . "*"));
echo $num;
  • 这不算数。 和 ..
  • 它是一个班轮
  • 我为此感到自豪

因为我也需要这个,所以我很好奇哪种方法最快。

我发现——如果你想要的只是文件数——Baba 的解决方案其他解决方案快得多。 我很惊讶。

自己试试吧:

<?php
define('MYDIR', '...');

foreach (array(1, 2, 3) as $i)
{
    $t = microtime(true);
    $count = run($i);
    echo "$i: $count (".(microtime(true) - $t)." s)\n";
}

function run ($n)
{
    $func = "countFiles$n";
    $x = 0;
    for ($f = 0; $f < 5000; $f++)
        $x = $func();
    return $x;
}

function countFiles1 ()
{
    $dir = opendir(MYDIR);
    $c = 0;
    while (($file = readdir($dir)) !== false)
        if (!in_array($file, array('.', '..')))
            $c++;
    closedir($dir);
    return $c;
}

function countFiles2 ()
{
    chdir(MYDIR);
    return count(glob("*"));
}

function countFiles3 () // Fastest method
{
    $f = new FilesystemIterator(MYDIR, FilesystemIterator::SKIP_DOTS);
    return iterator_count($f);
}
?>

测试运行:(显然, glob()不计算点文件)

1: 99 (0.4815571308136 s)
2: 98 (0.96104407310486 s)
3: 99 (0.26513481140137 s)

工作演示

<?php

$directory = "../images/team/harry/"; // dir location
if (glob($directory . "*.*") != false)
{
 $filecount = count(glob($directory . "*.*"));
 echo $filecount;
}
else
{
 echo 0;
}

?>

我用这个:

count(glob("yourdir/*",GLOB_BRACE))
<?php echo(count(array_slice(scandir($directory),2))); ?>

array_slicesubstr函数类似,只是它适用于数组。

例如,这将从数组中删除前两个数组键:

$key_zero_one = array_slice($someArray, 0, 2);

如果您省略第一个参数,就像在第一个示例中一样,数组将不包含前两个键/值对 *('.' 和 '..')。

根据接受的答案,这是一种递归计算目录中所有文件的方法:

iterator_count(
    new \RecursiveIteratorIterator(
        new \RecursiveDirectoryIterator('/your/directory/here/', \FilesystemIterator::SKIP_DOTS)
    )
)
$it = new filesystemiterator(dirname("Enter directory here"));
printf("There were %d Files", iterator_count($it));
echo("<br/>");
    foreach ($it as $fileinfo) {
        echo $fileinfo->getFilename() . "<br/>\n";
    } 

这应该可以在 dirname 中输入目录。 让魔法发生。

也许对某人有用。 在 Windows 系统上,您可以通过调用 dir 命令让 Windows 完成这项工作。 我使用绝对路径,例如E:/mydir/mysubdir

<?php 
$mydir='E:/mydir/mysubdir';
$dir=str_replace('/','\\',$mydir);
$total = exec('dir '.$dir.' /b/a-d | find /v /c "::"');
$files = glob('uploads/*');
$count = 0;
$totalCount = 0;
$subFileCount = 0;
foreach ($files as $file) 
{  
    global $count, $totalCount;
    if(is_dir($file))
    {
        $totalCount += getFileCount($file);
    }
    if(is_file($file))
    {
        $count++;  
    }  
}

function getFileCount($dir)
{
    global $subFileCount;
    if(is_dir($dir))
    {
        $subfiles = glob($dir.'/*');
        if(count($subfiles))
        {      
            foreach ($subfiles as $file) 
            {
                getFileCount($file);
            }
        }
    }
    if(is_file($dir))
    {
        $subFileCount++;
    }
    return $subFileCount;
}

$totalFilesCount = $count + $totalCount; 
echo 'Total Files Count ' . $totalFilesCount;

这是一个相当快的 PHP Linux 函数。 有点脏,但它完成了工作!

$dir - 目录路径

$type - f、d 或 false(默认)

f - 仅返回文件数

d - 仅返回文件夹计数

false - 返回文件和文件夹总数

function folderfiles($dir, $type=false) {
    $f = escapeshellarg($dir);
    if($type == 'f') {
        $io = popen ( '/usr/bin/find ' . $f . ' -type f | wc -l', 'r' );
    } elseif($type == 'd') {
        $io = popen ( '/usr/bin/find ' . $f . ' -type d | wc -l', 'r' );
    } else {
        $io = popen ( '/usr/bin/find ' . $f . ' | wc -l', 'r' );
    }

    $size = fgets ( $io, 4096);
    pclose ( $io );
    return $size;
}

您可以调整以适应您的需求。

请注意,这不适用于 Windows。

  simple code add for file .php then your folder which number of file to count its      

    $directory = "images/icons";
    $files = scandir($directory);
    for($i = 0 ; $i < count($files) ; $i++){
        if($files[$i] !='.' && $files[$i] !='..')
        { echo $files[$i]; echo "<br>";
            $file_new[] = $files[$i];
        }
    }
    echo $num_files = count($file_new);

简单的添加完成....

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM