PHP實現遞迴迴圈每一個目錄程式

來源:互聯網
上載者:User
 代碼如下 複製代碼

<?php
class listdir{
var $depth;
var $dirname;
var $list;
var $tostring;

function listdir($dir){
$this->dirname=$dir;
$this->depth=0;
$this->tostring=”";
}

//把結果儲存進多維陣列
function getlist($dir=”"){
if($dir==”")$dir=$this->dirname;
$d=@dir($dir);
while(false!==($item=$d->read()))
{
if($item!=”.”&&$item!=”..”)
{
$path=$dir.”/”.$item;
if(is_dir($path)){
$this->depth+=1;
$this->getlist($path);
}else{
$this->list[$this->depth][]=$item;
}
}
}
$this->list[$this->depth]['directory']=$dir;
$this->depth-=1;
$d->close();
return $this->list;
}

//字元竄化結果

function tostring($dir=”"){
if($dir==”")$dir=$this->dirname;
$d=@dir($dir);
$this->tostring.=”<UL>n”;
$this->tostring.=”Directory:”.$dir.”n”;
while(false!==($item=$d->read()))
{
if($item!=”.”&&$item!=”..”)
{
$path=$dir.”/”.$item;
if(is_dir($path)){
$this->depth+=1;
$this->tostring($path);
}else{
$this->tostring.=”<LI>”.$item.”</LI>n”;
}
}
}
$this->depth-=1;
$d->close();
$this->tostring.=”</UL>n”;
return $this->tostring;
}
}
$wapdir=”jquery”;
$d=new listdir($wapdir);
echo $d->tostring();
?>

要刪除一個空的目錄很簡單~一個
 
rmdir() 函數就可以搞定,但是要刪除一個非空目錄,將不能進行快速的刪除,必須先將目錄中檔案刪除,但是目錄裡可能還會有子目錄所以要進行遞迴刪除~下面是我的例子~
 

 代碼如下 複製代碼
<?php
function deletedir($dir){
      if(!handle=@opendir($dir)){     //檢測要開啟目錄是否存在
               die("沒有該目錄");
      }
     while(false !==($file=readdir($handle))){
               if($file!=="."&&$file!==".."){       //排除目前的目錄與父級目錄
                            $file=$dir .DIRECTORY_SEPARATOR. $file;
                            if(is_dir($file)){
                                  deletedir($file);
                            }else{
                                  if(@unlink($file)){
                                         echo "檔案<b>$file</b>刪除成功。<br>";
                                  }else{
                                          echo  "檔案<b>$file</b>刪除失敗!<br>";
                                 }
                }
     }
    if(@rmdir($dir)){
           echo "目錄<b>$dir</b>刪除成功了。<br>n";
    }else{
           echo "目錄<b>$dir</b>刪除失敗!<br>n";
  }
}
 
//測試程式
$dir="/var/www/test";
deletedir($dir);
?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.