diff --git a/src/Event/Http/Psr15Handler.php b/src/Event/Http/Psr15Handler.php index 79ea99e1e..b263ef928 100644 --- a/src/Event/Http/Psr15Handler.php +++ b/src/Event/Http/Psr15Handler.php @@ -16,6 +16,8 @@ public function __construct(RequestHandlerInterface $psr15Handler) public function handleRequest(HttpRequestEvent $event, Context $context): HttpResponse { + Psr7Bridge::cleanupUploadedFiles(); + $request = Psr7Bridge::convertRequest($event, $context); $response = $this->psr15Handler->handle($request); diff --git a/src/Event/Http/Psr7Bridge.php b/src/Event/Http/Psr7Bridge.php index 2db1406d0..667282016 100644 --- a/src/Event/Http/Psr7Bridge.php +++ b/src/Event/Http/Psr7Bridge.php @@ -18,6 +18,8 @@ */ final class Psr7Bridge { + private const UPLOADED_FILES_PREFIX = 'bref_upload_'; + /** * Create a PSR-7 server request from an AWS Lambda HTTP event. */ @@ -106,7 +108,7 @@ private static function parseBodyAndUploadedFiles(HttpRequestEvent $event): arra $parsedBody = []; foreach ($document->getParts() as $part) { if ($part->isFile()) { - $tmpPath = tempnam(sys_get_temp_dir(), 'bref_upload_'); + $tmpPath = tempnam(sys_get_temp_dir(), self::UPLOADED_FILES_PREFIX); if ($tmpPath === false) { throw new RuntimeException('Unable to create a temporary directory'); } @@ -166,4 +168,22 @@ private static function parseKeyAndInsertValueInArray(array &$array, string $key $pointer = $value; } + + /** + * Cleanup previously uploaded files. + */ + public static function cleanupUploadedFiles(): void + { + // See https://github.com/brefphp/bref/commit/c77d9f5abf021f29fa96b5720b7b84adbd199092#r137983026 + $tmpFiles = glob(sys_get_temp_dir() . '/' . self::UPLOADED_FILES_PREFIX . '[A-Za-z0-9][A-Za-z0-9][A-Za-z0-9][A-Za-z0-9][A-Za-z0-9][A-Za-z0-9]'); + + if ($tmpFiles !== false) { + foreach ($tmpFiles as $file) { + if (is_file($file)) { + // Silence warnings, we don't want to crash the whole runtime + @unlink($file); + } + } + } + } }