在php中要刪除檔案我們需要使用php提供的unlink()檔案刪除函數,下面我來給大家詳細介紹利用unlink刪除檔案的方法,有需要的朋友可參考本教程。
unlink(filename,context)
例
| 代碼如下 |
複製代碼 |
if (unlink($file_delete)) { echo "The file was deleted successfully.", "n"; } else { echo "The specified file could not be deleted. Please try again.", "n"; } |
判斷檔案是否存在
| 代碼如下 |
複製代碼 |
$myfile = "./test1.txt"; if (file_exists($myfile)) { $result=unlink ($myfile); echo $result; } ?> |
大量刪除檔案
| 代碼如下 |
複製代碼 |
function delFileUnderDir( $dirName="../Smarty/templates/templates_c" ) { 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 ); } }delDirAndFile( 'www.bKjia.c0m'); |
例
刪除目錄下檔案並指定那些不刪除
| 代碼如下 |
複製代碼 |
header("content-Type: text/html; charset=utf-8"); //配置開始 $path=".";//在些設定所刪除的目錄.為目前的目錄 如:刪除path目錄,引號裡請添path; $guolv="del.php,install.php,path";//設定需要過濾的檔案或檔案夾用英文狀態下,號分隔 //配置結束 if($_GET['action']=="del"){ $file= array_values_recursive(recurdir($path,$guolv)); foreach($file as $k => $v){ remove_directory($v); } }else{ echo "您的配置如下
要刪除的目錄為: "; if($path==".")echo "目前的目錄";else echo $path; echo " 您要過濾的檔案或檔案夾有:".$guolv."
如果確認過濾請點擊此處開始刪除相應的目錄及目錄下的所有檔案,如果配置不正確請到檔案中修改 "; } //刪除目錄及檔案 function remove_directory($dir) { foreach(glob($dir) as $fn) { echo " removing $fn n"; if (!is_writable($fn))@chmod($fn, 0777); if(is_dir($fn)){@rmdir($fn);}else{@unlink($fn);} } } //掃描目錄 function recurdir($pathname,$guolv='del.php') { $result=array();$temp=array(); //檢查目錄是否有效和可讀 if(!is_dir($pathname) || !is_readable($pathname)) return null; //得到目錄下的所有檔案夾 $allfiles=scandir($pathname); foreach($allfiles as $key => $filename) { //如果是“.”或者“..”的話則略過 if(in_array($filename,array('.','..')))continue; if(count($guolv)>0){$lv=explode(",",$guolv);if(in_array($filename,$lv))continue;} //得到檔案完整名字 $fullname =$pathname . "/" .$filename; //如果該檔案是目錄的話,遞迴調用recurdir $temp[]=$fullname; if(is_dir($fullname)){ $nowpath=explode("/",$fullname); if(count($guolv)>0){$lv=explode(",",$guolv);if(in_array($nowpath[count($nowpath)-1],$lv))continue;} $result[$filename] = recurdir($fullname);} } //最後把臨時數組中的內容添加到結果數組,確保目錄在前,檔案在後 foreach($temp as $f){ $result[]=$f; } return $result; } //擷取所有檔案 function array_values_recursive($ary) { $lst = array(); foreach( array_keys($ary) as $k ){ $v = $ary[$k]; if (is_array($v)) {$lst = array_merge( $lst, array_values_recursive($v));}else{$lst[] = $v;} } return $lst; } ?>
|
http://www.bkjia.com/PHPjc/633078.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/633078.htmlTechArticle在php中要刪除檔案我們需要使用php提供的unlink()檔案刪除函數,下面我來給大家詳細介紹利用unlink刪除檔案的方法,有需要的朋友可參考本教...