1. 程式人生 > >tp5實現刪除伺服器或本地檔案和資料夾

tp5實現刪除伺服器或本地檔案和資料夾

一   .因為客戶的伺服器記憶體比較小,為了方便後期的有利管理,需要及時的刪除不需要的圖片及檔案

下面介紹方法,採用的是ThinkPHP5.0框架

1. 先來看下我的結構目錄:


可以看到我所有的檔案都儲存在public/uploads下邊的以日期命名的資料夾中,

這裡採用了tp5的file類,有興趣的可以去研究下,這裡我用到了  unlink(),以及rmdir()的方法來刪除資料夾

和資料夾下邊的檔案,

由於,tp5有限制,要求刪除的資料夾下邊必須不能有檔案,所以如果直接刪除資料夾的話,會提示你沒有許可權

這裡需要迴圈一下資料夾下的檔案,分別刪除檔案,然後再刪除資料夾,好了,廢話不多講,下邊上說明:

二:在你的控制器其中寫入下面這個方法,不需要做任何改動,這個方法的作用是迴圈刪除資料夾下的檔案

借用了網上其他網友的改進方法,如下所示:

public function delDirAndFile($path, $delDir = FALSE) {
    if (is_array($path)) {
        foreach ($path as $subPath)
            delDirAndFile($subPath, $delDir);
    }
    if (is_dir($path)) {
        $handle = opendir($path);
        if ($handle) {
            while (false !== 
( $item = readdir($handle) )) { if ($item != "." && $item != "..") is_dir("$path/$item") ? delDirAndFile("$path/$item", $delDir) : unlink("$path/$item"); } closedir($handle); if ($delDir) return rmdir($path); } } else
{ if (file_exists($path)) { return unlink($path); } else { return FALSE; } } clearstatcache(); }

然後,我們就可以來呼叫這個方法來進行刪除操作了,如下所示:

//刪除全部檔案的方法
public function delSave(){
    $path=request()->param('path');
    $this->delDirAndFile(ROOT_PATH . 'public' . DS . 'uploads'.DS.$path);
    rmdir(ROOT_PATH . 'public' . DS . 'uploads'.DS.$path);
    return $this->success('刪除成功','del');
}

這裡$path指的是,你需要刪除的資料夾名,例如20180715,

如果,你要刪除uploads/20180715/1.jpg,那麼只需要把$path的值賦值為20180715即可。

三:如果你只需要制定刪除特別的檔案,那就更容易了,只需要用以下的方法即可:

//刪除單個檔案方法
public function test(){$filename = ROOT_PATH . 'public' . DS . 'uploads/20180628/1.jpg';
    if(file_exists($filename)){
        unlink($filename);
    }else{
        return '我已經被刪除了哦!';
    }
}
好了,刪除檔案的介紹到此結束,歡迎大家指教