簡體   English   中英

使用 unlink() PHP 時出現“是目錄”錯誤

[英]"Is a directory" error when using unlink() PHP

我正在嘗試一個簡單的事情。 從 post 方法獲取圖像,將這些圖像移動到我的 public/images 文件夾中,如果出現任何阻止代碼繼續運行的錯誤(例如我使用preg_match()檢查的不受支持的文件類型),則回滾整個事情,換句話說,刪除已經移動到文件夾中的文件。

問題是,當我嘗試使用unlink()時,我得到了這個“是目錄”錯誤。 我不是要刪除目錄! 我正在嘗試刪除文件!

我利用is_file()is_dir()file_exists()來檢查所有內容,並且所有內容都指向文件。 我幾乎整天都在試圖弄清楚發生了什么,但沒有成功。 我幾乎要放棄這件事了。

我在 Ubuntu 20.04 上,使用流明 8 和 PHP 7.4。 這是我的 controller 代碼:

<?php

namespace App\Http\Controllers;

use App\Models\Insumo;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class InsumosController extends BaseController
{
    public function __construct()
    {
        $this->classe = Insumo::class;
    }

    public function store(Request $request)
    {
        try {
            DB::beginTransaction();

            $images = [
                'mainImg' => "",
                'img1' => "",
                'img2' => "",
                'img3' => "",
                'img4' => ""
            ];

            $filesKeys = $request->files->keys();

            foreach ($filesKeys as $fileKey) {
                $pattern = "/^image\/(jpeg|jpg|bmp|png|gif)$/";
                $mimeType = $request->file($fileKey)->getMimeType();

                if (!preg_match($pattern, $mimeType)) {
                    throw new \Exception('Not supported file', 415);
                }

                $insumoNome = lcfirst(str_replace(' ', '', $request->nome));
                $ext = "." . $request->file($fileKey)->extension();
                $newName = $insumoNome . "-" . $fileKey . "-" . bin2hex(random_bytes(5)) . $ext;
                $images[$fileKey] = $newName;

                $request->file($fileKey)->move('images', $newName);
            }

            $insumo = Insumo::create([
                'nome' => $request->nome,
                'descricao' => $request->descricao,
                'mainImg' => $images['mainImg'],
                'img1' => $images['img1'],
                'img2' => $images['img2'],
                'img3' => $images['img3'],
                'img4' => $images['img4'],
            ]);

            DB::commit();

            return response()->json($insumo, 201);
        } catch (\Exception $e) {
            DB::rollBack();

            $imagesDir = __DIR__ . '/../../../public/images/';

            foreach ($images as $image) {

                if (file_exists($imagesDir . $image)) {
                    $imagesPath = $imagesDir . $image;
                    unlink($imagesPath);
                }
            }

            return response()->json($e->getMessage(), $e->getCode());
        }
    }
}

除了unlink()之外,所有代碼似乎都按我的預期工作。 會有好心人幫我解決這個問題嗎?

經過將近一天的時間試圖弄清楚發生了什么,並且在我提交這個問題的那一刻,我在腦海中通過檢查我在foreach中的$image變量,你猜怎么着? 有時它會變空。

嗯,發現問題了...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM