2016-06-07 91 views
1

我想检查一个文件夹是否至少包含1个真实文件。我试过这个代码:如何检查文件夹是否仅包含使用php的文件

$dir = "/dir/you/want/to/scan"; 
$handle = opendir($dir); 
$folders = 0; 
$files = 0; 

while(false !== ($filename = readdir($handle))){ 
    if(($filename != '.') && ($filename != '..')){ 
     if(is_dir($filename)){ 
      $folders++; 
     } else { 
      $files++; 
     } 
    } 
} 

echo 'Number of folders: '.$folders; 
echo '<br />'; 
echo 'Number of files: '.$files; 

当在文件夹中scan是1个子文件夹和2个真实文件;上面的代码给了我作为输出:

Number of folders: 0

Number of files: 3

如此看来,一个子文件夹被视为一个文件。但我只想要检查真实文件。我怎么能做到这一点?

+0

内做到这一点帮助您:https://secure.php.net/manual/en/ function.scandir.php#87527?并检查数组是否为空()。 – 2016-06-07 11:38:40

+0

[PHP:如何在没有列出子目录的情况下列出目录中的文件]的可能副本(http://stackoverflow.com/questions/7684881/php-how-to-list-files-in-a-directory-without-list -subdirectories) – Thamilan

回答

2

您可以使用​​3210轻松完成此任务:

$dir = "/dir/you/want/to/scan"; 
$folders = glob($dir . '/*', GLOB_ONLYDIR); 
$files = array_filter(glob($dir . '/*'), 'is_file'); 

echo 'Number of folders: ' . count($folders); 
echo '<br />'; 
echo 'Number of files: ' . count($files); 
+0

太棒了!这很好用!感谢您的解决方案 –

3

根据您的第一行,您指定的路径与脚本路径不同,您应该在is_dir if-clause中结合$ dir和$ filename。

为什么?

因为如果你的脚本是:

/var/web/www/script.php

,你检查$ DIR:

的/ etc/httpd的

包含子文件夹“conf”,脚本将检查子文件夹/ var/web/www/conf

+0

它的脚本中是'$ dir',但这是正确的答案。 –

1

您可以使用scandir

SCANDIR - 列出文件和目录的指定路径

<?php 
$dir = "../test"; 
$handle = scandir($dir); 
$folders = 0; 
$files = 0; 
foreach($handle as $filename) 
{ 
    if(($filename != '.') && ($filename != '..')) 
    { 
     if(is_dir($filename)) 
     { 
      $folders++; 
     } 
     else 
     { 
      $files++; 
     } 
    } 
} 

echo 'Number of folders: '.$folders; 
echo '<br />'; 
echo 'Number of files: '.$files; 
?> 
相关问题