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

后端 未结 4 1079
一个人的身影
一个人的身影 2020-12-07 03:34

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

相关标签:
4条回答
  • 2020-12-07 04:12

    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';
        }
    
    }
    ?>
    
    0 讨论(0)
  • 2020-12-07 04:19

    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))
    
    0 讨论(0)
  • 2020-12-07 04:35

    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.

    0 讨论(0)
  • 2020-12-07 04:37

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

    0 讨论(0)
提交回复
热议问题