Files
MediaCollectorLibary/app/Controllers/ImageController.php
Lars Behrends 73d8441787 i dont know
2025-10-20 23:40:55 +02:00

54 lines
1.6 KiB
PHP

<?php
namespace App\Controllers;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
class ImageController extends Controller
{
/**
* Serve an image from internal storage
* @param Request $request
* @param Response $response
* @param array $args
* @return Response
*/
public function serve(Request $request, Response $response, $args): Response
{
$imagePath = $args['path'] ?? '';
// Security: Prevent directory traversal
$imagePath = str_replace(['../', '..\\'], '', $imagePath);
$fullPath = __DIR__ . '/../../storage/images/' . $imagePath;
// Check if file exists
if (!file_exists($fullPath)) {
return $response->withStatus(404, 'Image not found');
}
// Get file extension and set appropriate content type
$extension = strtolower(pathinfo($fullPath, PATHINFO_EXTENSION));
$contentTypes = [
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
'webp' => 'image/webp',
'svg' => 'image/svg+xml',
];
$contentType = $contentTypes[$extension] ?? 'application/octet-stream';
// Read and serve the file
$fileContent = file_get_contents($fullPath);
$response = $response->withHeader('Content-Type', $contentType);
$response = $response->withHeader('Cache-Control', 'public, max-age=3600'); // Cache for 1 hour
$response->getBody()->write($fileContent);
return $response;
}
}