![](/img/trans.png)
[英]How to delete all folders and files in a directory except a specific folder in PHP
[英]How to delete all files except one from a directory using PHP?
我有幾個目錄,其中有一些文件:
/test1/123.jpg
/test1/124.jpg
/test1/125.jpg
/test2/123.jpg
/test2/124.jpg
我想刪除除/test1/124.jpg or /test2/124.jpg
之外的所有/test1/124.jpg or /test2/124.jpg
?
我知道目錄名和文件名。 有沒有辦法在帶有 php 的 Linux 環境中做到這一點,也許unlink
?
只需編輯 $dir 和 $leave_files 即可編輯位置和文件。
$dir = 'test1';
$leave_files = array('124.jpg', '123.png');
foreach( glob("$dir/*") as $file ) {
if( !in_array(basename($file), $leave_files) ){
unlink($file);
}
}
您將為每個目錄運行一次。
如果目標目錄與此腳本不在同一文件夾中,請記住將 $dir 設為完整路徑(沒有尾部斜杠)。
也許有點粗糙,但如果你在 Linux 系統上,你可以這樣做(假設你在正確的目錄中):
<?php shell_exec('rm $(ls * | grep -v '.$fileYouWantToKeep.')'); ?>
如果包含任何用戶輸入,您顯然需要過濾該變量。
8 年前我寫了這個被接受的快速黑客,但請考慮到
rm
和mv
刪除和移動 shell 命令。shell_exec
上捕獲錯誤也不是微不足道的,因為您沒有像使用exec或system這樣的替代方案那樣獲得退出代碼)但是,它的優點是可以在單個 shell 命令中運行所有刪除操作,並且不需要對每個處理過的文件進行額外的排除查找,這使得它在高刪除率與保留率的情況下運行得非常快,如果您正在尋找性能:
for ($i=1;$i<=2;$i++){
shell_exec ('mv /test'.$i.'/124.jpg /test'.$i.'/keep.jpg');
shell_exec ('rm /test'.$i.'/12*.jpg');
shell_exec ('mv /test'.$i.'/keep.jpg /test'.$i.'/124.jpg');
}
無論如何,如果您在這里查看其他一些提出基於取消鏈接的解決方案的答案是在我的之后添加的,這(如下面的評論中所述)是一種更好的方法,我也建議這樣做
添加錯誤處理,因為當文件正在使用或不允許腳本執行用戶修改它時, unlink
可能會因權限問題無法刪除現有文件。
總是ini_get('
max_execution_time ');
在運行腳本處理不知不覺長的文件列表之前檢查您的腳本執行超時設置(並考慮在必要時使用set_time_limit為您的腳本擴展它)。
這是另一種選擇:
<?php
$dirList = array('/path/to/dir1','/path/to/dir2'); //List of Dirs with files to be deleted. No trailing slash
$saved = array('path/to/file1','path/to/file2'); //List of files to be saved, no leading slash
foreach($dirList as $directory){
$list = scandir($directory);
foreach($list as $file){
if(!is_int(array_seach($directory.'/'.$file,$saved))){ //Array search returns key if needle exists, so we check if it does not return int
unlink($file);
}
}
}
?>
我現在無法訪問我的服務器,所以我還沒有測試它,但我認為它應該可以工作。 首先在一些測試目錄上嘗試一下,看看它是否有效。
您可以將文件移動到臨時文件夾,然后刪除該文件夾,創建一個新的粉絲並使用舊文件夾的名稱移動文件夾,然后將照片移回,刪除 tmp 文件夾。 $ 利潤 $
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.