How to check a path is a file or folder in PHP

主宰稳场 提交于 2019-11-26 23:37:33

问题


I use scandir() to search files recursively. But if the file path directs to a file not a folder, there will be a warning. How can I check the path whether it directs a file or folder?

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?




}
?>

Thanks!


回答1:


Have a look into is_dir() and 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';
    }

}
?>



回答2:


is_dir() should tell you if a path is a directory or not.




回答3:


You can check whether if the variable has file extension or not.

This "if" will gets files only :

if (pathinfo($file, PATHINFO_EXTENSION))

and this "if" will gets directories only:

if (!pathinfo($file, PATHINFO_EXTENSION))



回答4:


You can also use DirectoryIterator (class)

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

Also, you may check is_file and is_dir.



来源:https://stackoverflow.com/questions/18903719/how-to-check-a-path-is-a-file-or-folder-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!