Skip to content

Commit

Permalink
Merge pull request #1726 from brefphp/cleanup-uploaded-files
Browse files Browse the repository at this point in the history
Cleanup uploaded files for PSR-15 handlers
  • Loading branch information
mnapoli authored Jan 31, 2024
2 parents d789c22 + 23f8174 commit 44bdff0
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
2 changes: 2 additions & 0 deletions src/Event/Http/Psr15Handler.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
22 changes: 21 additions & 1 deletion src/Event/Http/Psr7Bridge.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down Expand Up @@ -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');
}
Expand Down Expand Up @@ -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);
}
}
}
}
}

0 comments on commit 44bdff0

Please sign in to comment.