diff --git a/CHANGELOG.md b/CHANGELOG.md index 75ff0ff3c..c6e58e69a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## [Unreleased](https://github.com/laravel/octane/compare/v1.2.1...1.x) +### Added + +- Listener for removing temporary files which were created during uploading _(must be enabled manually for existing applications)_ ([#477](https://github.com/laravel/octane/pull/477)) + ## [v1.2.1](https://github.com/laravel/octane/compare/v1.2.1...v1.2.1) - 2022-02-08 ### Changed diff --git a/config/octane.php b/config/octane.php index 20007c7ac..818ee7036 100644 --- a/config/octane.php +++ b/config/octane.php @@ -16,6 +16,7 @@ use Laravel\Octane\Listeners\EnsureUploadedFilesAreValid; use Laravel\Octane\Listeners\EnsureUploadedFilesCanBeMoved; use Laravel\Octane\Listeners\FlushTemporaryContainerInstances; +use Laravel\Octane\Listeners\FlushUploadedFiles; use Laravel\Octane\Listeners\ReportException; use Laravel\Octane\Listeners\StopWorkerIfNecessary; use Laravel\Octane\Octane; @@ -78,7 +79,7 @@ ], RequestTerminated::class => [ - // + // FlushUploadedFiles::class, ], TaskReceived::class => [ diff --git a/src/Listeners/FlushUploadedFiles.php b/src/Listeners/FlushUploadedFiles.php new file mode 100644 index 000000000..2c18ce21d --- /dev/null +++ b/src/Listeners/FlushUploadedFiles.php @@ -0,0 +1,30 @@ +request->files->all() as $file) { + if (! $file instanceof SplFileInfo || + ! is_string($path = $file->getRealPath())) { + continue; + } + + clearstatcache(true, $path); + + if (is_file($path)) { + unlink($path); + } + } + } +} diff --git a/tests/Listeners/FlushUploadedFilesTest.php b/tests/Listeners/FlushUploadedFilesTest.php new file mode 100644 index 000000000..42fbf72a6 --- /dev/null +++ b/tests/Listeners/FlushUploadedFilesTest.php @@ -0,0 +1,53 @@ +files->add([ + new UploadedFile($file1path, Str::random()), + new UploadedFile($file2path, Str::random()), + new UploadedFile($file3path, Str::random()), + ]); + + $this->assertTrue(\rename($file3path, $file3newPath = $file3path.Str::random())); + + $this->assertFileExists($file1path); + $this->assertFileExists($file2path); + $this->assertFileExists($file3newPath); + + $event = new \stdClass(); + $event->request = $request; + + (new FlushUploadedFiles)->handle($event); + + $this->assertFileDoesNotExist($file1path); + $this->assertFileDoesNotExist($file2path); + $this->assertFileExists($file3newPath); // still exists + } finally { + foreach ([$file1path, $file2path, $file3newPath] as $fileName) { + if (\is_file($fileName)) { + \unlink($fileName); + } + } + } + } +}