我使用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?
}
?>
谢谢!
答案 0 :(得分:6)
查看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';
}
}
?>
答案 1 :(得分:3)
is_dir()应该告诉您路径是否是目录。
答案 2 :(得分:1)
您可以检查变量是否包含文件扩展名。
此“if”仅获取文件:
if (pathinfo($file, PATHINFO_EXTENSION))
这个“if”只会获取目录:
if (!pathinfo($file, PATHINFO_EXTENSION))
答案 3 :(得分:0)
您还可以使用DirectoryIterator(class)
$path = 'your path';
$dir = new DirectoryIterator(realpath($path));
foreach ($dir as $fileInfo) {
if($fileInfo->isFile()) {
// it's a file
}
}