php擷取並刪除目錄及目錄下所有的檔案執行個體_PHP教程

來源:互聯網
上載者:User
今天我們一起來看看在php中擷取目錄及刪除目錄中檔案或指定目錄中檔案執行個體,希望此方法對各位朋友會帶來協助。

用php程式刪除目錄和檔案比到ftp刪除有很多優勢。首先進ftp就比較麻煩,然後刪除大量檔案的時候ftp刪除很慢,還有就是程式只想刪除檔案夾下面的檔案,而保留目錄結構,可以用php來輕鬆的實現,再有比如產生的日誌、緩衝要清除用程式來完成顯然輕鬆的多。

第一步,PHP擷取目錄下面所有檔案和檔案夾

代碼如下 複製代碼

$dir = "D:/"; //要擷取的目錄

echo "********** 擷取目錄下所有檔案和檔案夾 ***********

";

//先判斷指定的路徑是不是一個檔案夾

if (is_dir($dir)){

if ($dh = opendir($dir)){

while (($file = readdir($dh))!= false){

//檔案名稱的全路徑 包含檔案名稱

$filePath = $dir.$file;

//擷取檔案修改時間

$fmt = filemtime($filePath);

echo "(".date("Y-m-d H:i:s",$fmt).") ".$filePath."
";

}

closedir($dh);

}

}

?>


第2步:刪除目錄及目錄下所有的檔案

代碼如下 複製代碼


function delDirAndFile( $dirName ){

if ( $handle = opendir( "$dirName" ) ) {

while ( false !== ( $item = readdir( $handle ) ) ) {

if ( $item != "." && $item != ".." ) {

if ( is_dir( "$dirName/$item" ) ) {

delDirAndFile( "$dirName/$item" );

} else {

if( unlink( "$dirName/$item" ) )echo "已刪除檔案: $dirName/$item
n";

}

}

}

closedir( $handle );

if( rmdir( $dirName ) ) echo "成功刪除目錄: $dirName
n";

}

}


第3步:刪除目錄下面的檔案,不刪除目錄

代碼如下 複製代碼


function delFileUnderDir( $dirName ){

if ( $handle = opendir( "$dirName" ) ) {

while ( false !== ( $item = readdir( $handle ) ) ) {

if ( $item != "." && $item != ".." ) {

if ( is_dir( "$dirName/$item" ) ) {

delFileUnderDir( "$dirName/$item" );

} else {

if( unlink( "$dirName/$item" ) ) echo "已刪除檔案:$dirName/$item
n";

}

}

}

closedir( $handle );

}

}

小結

這個我們先是從擷取目錄所有所檔案與目錄開始然後在基礎上進行刪除操作。

http://www.bkjia.com/PHPjc/632719.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/632719.htmlTechArticle今天我們一起來看看在php中擷取目錄及刪除目錄中檔案或指定目錄中檔案執行個體,希望此方法對各位朋友會帶來協助。 用php程式刪除目錄和文...

  • 聯繫我們

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