duangang3832 2012-01-11 03:01
浏览 82
已采纳

如何使用php检索特定文件夹中的所有文件名

say, in my webserver there is a folder call upload_files then one of my php page should grab the all the file name in that folder i have googled but so far the file name returned is only the page the user browsering thanks

  • 写回答

3条回答 默认 最新

  • douxing6532 2012-01-11 03:28
    关注

    There are many ways of retrieving folder content like glob, scandir, DirectoryIterator and RecursiveDirectoryIterator, personaly I would recommend you to check DirectoryIterator as it has big potential.

    Example using scandir method

    $dirname = getcwd();
    
    $dir = scandir($dirname);
    
    foreach($dir as $i => $filename)
    {
        if($filename == '.' || $filename == '..')
            continue;
    
        var_dump($filename);
    }
    

    Example using DirectoryIterator class

    $dirname = getcwd();
    
    $dir = new DirectoryIterator($dirname);
    
    foreach ($dir as $path => $splFileInfo)
    {
        if ($splFileInfo->isDir())
            continue;
    
        // do what you have to do with your files
    
        //example: get filename
        var_dump($splFileInfo->getFilename());
    }
    

    Here is less common example using RecursiveDirectoryIterator class:

    //use current working directory, can be changed to directory of your choice
    $dirname = getcwd();
    
    $splDirectoryIterator = new RecursiveDirectoryIterator($dirname);
    
    $splIterator = new RecursiveIteratorIterator(
        $splDirectoryIterator, RecursiveIteratorIterator::SELF_FIRST
    );
    
    foreach ($splIterator as $path => $splFileInfo)
    {
        if ($splFileInfo->isDir())
            continue;
    
        // do what you have to do with your files
    
        //example: get filename
        var_dump($splFileInfo->getFilename());
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?