如何在 Laravel 中刪除公共資料夾中的檔案?
您可以使用 File facade 類。要使用 File facade,您需要包含如下所示的類:
use Illuminate\Support\Facades\File;
以下是一些示例,展示瞭如何從公共資料夾中刪除檔案。
公共資料夾中的檔案詳細資訊如下:
示例 1
使用 File facade 的 delete() 方法刪除檔案。delete() 方法將刪除給定的檔案。它可以接收單個檔案或檔案陣列作為輸入。您可以如下所示從公共資料夾中刪除單個檔案:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\File; class UserController extends Controller{ public function index() { $images = \File::allFiles(public_path('images')); $deletedFile = File::delete(app_path().'/images/'.$images[1]->getFilename()); if ($deletedFile == null) { echo "File deleted"; } } }
輸出
以上程式碼的輸出為:
File deleted
在公共資料夾中,您將看不到 img1.jpg 檔案。
示例 2
在 php 中使用 unlink() 方法
unlink(): 它有助於刪除給定的檔案。如果存在指向給定檔名的符號引用,則也會刪除該引用。
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class UserController extends Controller { public function index() { if (file_exists(public_path('images/img3.jpg'))){ $filedeleted = unlink(public_path('images/img3.jpg')); if ($filedeleted) { echo "File deleted"; } } else { echo 'Unable to delete the given file'; } } }
輸出
以上程式碼的輸出為:
File deleted
公共資料夾中的檔案如下:
示例 3
以下示例演示瞭如何刪除公共資料夾內的資料夾。File Facade 的 deleteDirectory() 方法用於刪除資料夾。此方法將完全刪除檔案以及資料夾。
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; use Illuminate\Support\Facades\File; class UserController extends Controller{ public function index() { $cssfolder = public_path('css'); $folderdetails = File::deleteDirectory($cssfolder); print_r($folderdetails); } }
輸出
以上程式碼的輸出為:
1
public_folder 如下所示:
示例 4
另一個示例有助於從給定資料夾中刪除多個檔案。為了測試,讓我們在公共資料夾內新增一個資料夾,如下所示:
在公共資料夾內添加了一個資料夾 testjs/。讓我們刪除其中存在的所有檔案。
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\File; class UserController extends Controller { public function index() { $files = File::allFiles(public_path('testjs')); print_r($files); foreach ($files as $file) { $deletedFile = File::delete(public_path('testjs/'.$file->getFilename())); } } }
輸出
以上程式碼的輸出為
Array( [0] => Symfony\Component\Finder\SplFileInfo Object( [relativePath:Symfony\Component\Finder\SplFileInfo:private] => [relativePathname:Symfony\Component\Finder\SplFileInfo:private] => script2.js [pathName:SplFileInfo:private] => C:\xampp\htdocs\laraveltest\public\testjs\script2.js [fileName:SplFileInfo:private] => script2.js ) [1] => Symfony\Component\Finder\SplFileInfo Object( [relativePath:Symfony\Component\Finder\SplFileInfo:private] => [relativePathname:Symfony\Component\Finder\SplFileInfo:private] => scripts.js [pathName:SplFileInfo:private] => C:\xampp\htdocs\laraveltest\public\testjs\scripts.js [fileName:SplFileInfo:private] => scripts.js ) )
廣告