【问题标题】:How to check a path is a file or folder in PHP如何检查路径是PHP中的文件或文件夹
【发布时间】:2013-09-19 19:51:38
【问题描述】:

我使用 scandir() 递归搜索文件。但如果文件路径指向文件而不是文件夹,则会出现警告。如何检查路径是否指向文件或文件夹?

enter code here
<?php

$path = "C:\\test_folder\\folder2\\folder4";
$sub_folder = scandir($path);
$num = count($sub_folder);
for ($i = 2; $i < $num; $i++)
{
...//if $sub_folder[$i] is a file but a folder, there will be a warning.
       How can I check $sub_folder[$i] before use it?




}
?>

谢谢!

【问题讨论】:

  • 一个非常快速的谷歌在 php 手册中给出了答案,bool is_dir (string $filename)

标签: php file scandir


【解决方案1】:

看看 is_dir() 和 is_file()

<?php

$path = "C:\\test_folder\\folder2\\folder4";
$sub_folder = scandir($path);
$num = count($sub_folder);
for ($i = 2; $i < $num; $i++)
{
    if(is_file($path.'\\'.$sub_folder[$i])){
        echo 'Warning';
    }

}
?>

【讨论】:

  • 谢谢!我之前用过is_dir()和is_file(),只是误用了$sub_folder[$i]作为参数,没有得到我想要的结果。
【解决方案2】:

is_dir() 应该告诉你路径是否是目录。

【讨论】:

    【解决方案3】:

    你可以检查变量是否有文件扩展名。

    这个“如果”只会获取文件:

    if (pathinfo($file, PATHINFO_EXTENSION))
    

    而这个“if”只会获取目录:

    if (!pathinfo($file, PATHINFO_EXTENSION))
    

    【讨论】:

      【解决方案4】:

      您也可以使用DirectoryIterator (class)

      $path = 'your path';
      $dir = new DirectoryIterator(realpath($path));
      foreach ($dir as $fileInfo) {
          if($fileInfo->isFile()) {
              // it's a file
          }
      }
      

      另外,您可以查看is_fileis_dir

      【讨论】:

        猜你喜欢
        • 2012-09-28
        • 2017-02-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多