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

asdk77 picture asdk77 · Sep 19, 2013 · Viewed 15.7k times · Source

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!

Answer

Andy  Gee picture Andy Gee · Sep 19, 2013

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';
    }

}
?>