public` and served through the `public/storage` symlink, * so an uploaded file is reachable from the site without a second copy. */ private const DISK = 'public'; /** * Sub-directory uploads land in, so a single flat folder cannot grow * unbounded and directory listings stay cheap to paginate. */ private const DIRECTORY = 'media'; /** * Store an uploaded image and return the URL to persist on the record. * * The filename is generated rather than taken from the client: an * attacker-supplied name is the usual way to smuggle a double extension * (`cover.php.jpg`) or a path traversal into a web-served directory. */ public function store(StoreMediaRequest $request): JsonResponse { $file = $request->file('file'); $path = $file->store(self::DIRECTORY, self::DISK); if ($path === false) { return response()->json(['message' => 'Image could not be stored.'], 500); } return response()->json([ 'data' => [ 'url' => Storage::disk(self::DISK)->url($path), 'path' => $path, 'name' => basename($path), 'size' => $file->getSize(), 'mime' => $file->getMimeType(), ], ], 201); } /** * Delete an uploaded image by its stored path. * * Only paths inside the upload directory are accepted, so a crafted * `../../.env` cannot be used to delete arbitrary files on the server. */ public function destroy(string $path): JsonResponse { $disk = Storage::disk(self::DISK); $clean = Str::start(Str::after($path, self::DIRECTORY.'/'), self::DIRECTORY.'/'); // `Str::after` returns the whole string when the prefix is absent, so // re-check the prefix explicitly before touching the disk. if (! str_starts_with($clean, self::DIRECTORY.'/') || str_contains($clean, '..')) { return response()->json(['message' => 'Invalid media path.'], 422); } if (! $disk->exists($clean)) { return response()->json(['message' => 'Media not found.'], 404); } $disk->delete($clean); return response()->json(['message' => 'Media deleted.']); } }