樹型結構列出指定目錄裡所有檔案的PHP類

來源:互聯網
上載者:User
<?
//以樹型結構列出指定目錄裡的所有檔案,如果你想知道自己某個目錄裡有哪些子目錄和檔案,可以調用這個類來查看,很方便的。

    # 示範的例子:
    $t = new TreeClimber( "asp" ); //建立物件,設定需要列出的目錄:在此為asp目錄
    echo arrayValuesToString( $t->getFileList( $t->getPath() ), "<BR>\n" );
    
    function arrayValuesToString( $ar, $nl="", $dolast=true ) {//調用函數
    $str = "";
    reset( $ar );
    $size = sizeof( $ar );
    $i = 1;
    while( list( $k, $v ) = each( $ar ) ) {
    if ( $dolast == false ) {
    if ( $i < $size ) {
        $str .= $ar[$k].$nl;
    }
    else {
        $str .= $ar[$k];
    }
    }
    else {
    $str .= $ar[$k].$nl;
    }
    $i++;
    }
    return $str;
    }
    ?>
    <?
    //以下為類檔案
    class TreeClimber {
    var $path;
    var $fileList = array();
    function TreeClimber( $path = "." ) {
    $this->path = $path;
    }
    
    # 存取路徑
    function getPath() { return $this->path; }
    function setPath( $v ) { $this->path = $v; }
    
    // 返回指定目錄裡的檔案清單,如果沒有指定目錄,將使用目前的目錄
    //如果不能開啟目錄(可能沒許可權或目錄不存在,將返回為空白
    //以遞迴方式進行
     function getFileList( $dirname=null, $returnDirs=false, $reset=true ) {
    if ( $dirname == null ) { $dirname = $this->path; }
    # else { $this->setPath( $dirname ); }
    # dout( "Recursing into $dirname..." );
    if ( $reset ) {  
    $this->fileList = array();
    }
    $dir = opendir( $dirname );
    if ( ! $dir ) {  
    print( "<B><FONT COLOR=#FF0000>注意: TreeClimber.getFileList( $dirname ): 不能開啟 $dirname!</FONT></B>" );
    return null;  
    }
    while( $file = readdir( $dir ) ) {
    if ( ereg( "^\.$", $file ) || ereg( "^\.\.$", $file ) ) continue;
    if ( is_dir( $dirname."/".$file ) ) {
    $this->getFileList( $dirname."/".$file, $returnDirs, false );
    if ( $returnDirs ) { $this->fileList[] = $dirname."/".$file;}
    }
    else { $this->fileList[] = $dirname."/".$file; }
    }
    sort( $this->fileList );
    return $this->fileList;
    }
    } //至此類結束
    ?>


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.