Last active
July 31, 2024 17:42
-
-
Save daveh/432e34761148750cfc27d04030694591 to your computer and use it in GitHub Desktop.
File Uploads in a REST API in PHP (source to accompany https://youtu.be/0C1s7E6-1mw)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
use Slim\Factory\AppFactory; | |
use Psr\Http\Message\ServerRequestInterface as Request; | |
use Psr\Http\Message\ResponseInterface as Response; | |
require dirname(__DIR__) . "/vendor/autoload.php"; | |
$app = AppFactory::create(); | |
$app->post('/api/images', function (Request $request, Response $response) { | |
$files = $request->getUploadedFiles(); | |
if ( ! array_key_exists("file", $files)) { | |
$response->getBody()->write(json_encode("'file' missing from request data")); | |
return $response->withHeader("Content-type", "application/json") | |
->withStatus(422); | |
} | |
$file = $files["file"]; | |
$error = $file->getError(); | |
if ($error !== UPLOAD_ERR_OK) { | |
return $response->withStatus(422); | |
} | |
if ($file->getSize() > 1000000) { | |
return $response->withStatus(422); | |
} | |
$media_types = ["image/png", "image/jpeg"]; | |
if ( ! in_array($file->getClientMediaType(), $media_types)) { | |
return $response->withStatus(422); | |
} | |
try { | |
$file->moveTo(dirname(__DIR__) . "/uploads/" . $file->getClientFilename()); | |
return $response->withStatus(201); | |
} catch (Exception $e) { | |
return $response->withStatus(500); | |
} | |
}); | |
$app->get("/api/images/{id}", function (Request $request, Response $response) { | |
$path = dirname(__DIR__) . "/uploads/fish.png"; | |
$contents = file_get_contents($path); | |
$response->getBody()->write($contents); | |
return $response->withHeader("Content-type", "image/png"); | |
}); | |
$app->delete("/api/images/{id}", function (Request $request, Response $response) { | |
$path = dirname(__DIR__) . "/uploads/fish.png"; | |
unlink($path); | |
return $response; | |
}); | |
$app->run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment