php一个递归读取目录文件脚本

这个脚本写的非常好,值得参考。

<?php
function recurdir($thedir)
{
    //first attempt to open the directory
    try{
        if($adir=opendir($thedir))
        {
            //scan through the directory
            while(false!==($anitem=readdir($adir)))
            {
                //do not count the . or ..  in the directory 
                if($anitem!='.'&&$anitem!='..')
                {
                    //now ,if it is another directory,then you indent a bit
                    //and go recursive
                    if(is_dir($thedir.'/'.$anitem))
                    {
                      ?> <span style="font-weight:bold;"><?php echo $anitem;?></span>
                      <div style="margin-left:20px;"><?php recurdir($thedir.'/'.$anitem);?>
                      </div>
                      <?php
                    }
                    else if(is_file($thedir.'/'.$anitem))
                    {
                        echo $anitem.'<br/>';
                        
                    }
                }
            }
        }else {
            throw new Exception("Sorry,directory could not be opened");
        }
    }catch(Exception $e){
        echo $e->getmessage();
    }
}

//recurdir("../google/zhanguo/demo2/");
recurdir('.');

?>
    
            
                    
                     

读取截图:

注意,opendir不能打开远程目录,即以http://开头的目录,即使是本地的http也不行。

opendir("http://localhost/php"); 也会报错: failed to open dir: not implemented 这是这个问题

原文地址:https://www.cnblogs.com/youxin/p/2769753.html