diff --git a/src/Symfony/Component/HttpFoundation/BinaryFileResponse.php b/src/Symfony/Component/HttpFoundation/BinaryFileResponse.php index 986dde1ac6..e01f3dc717 100644 --- a/src/Symfony/Component/HttpFoundation/BinaryFileResponse.php +++ b/src/Symfony/Component/HttpFoundation/BinaryFileResponse.php @@ -30,6 +30,7 @@ class BinaryFileResponse extends Response protected $file; protected $offset; protected $maxlen; + protected $deleteFileAfterSend = false; /** * Constructor. @@ -258,6 +259,10 @@ class BinaryFileResponse extends Response fclose($out); fclose($file); + + if ($this->deleteFileAfterSend) { + unlink($this->file->getPathname()); + } } /** @@ -289,4 +294,19 @@ class BinaryFileResponse extends Response { self::$trustXSendfileTypeHeader = true; } + + /** + * If this is set to true, the file will be unlinked after the request is send + * Note: If the X-Sendfile header is used, the deleteFileAfterSend setting will not be used. + * @param bool $shouldDelete + * + * @return BinaryFileResponse + */ + public function deleteFileAfterSend($shouldDelete) + { + $this->deleteFileAfterSend = $shouldDelete; + + return $this; + } + } diff --git a/src/Symfony/Component/HttpFoundation/Tests/BinaryFileResponseTest.php b/src/Symfony/Component/HttpFoundation/Tests/BinaryFileResponseTest.php index 397192b885..d77a97956f 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/BinaryFileResponseTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/BinaryFileResponseTest.php @@ -193,6 +193,24 @@ class BinaryFileResponseTest extends ResponseTestCase $this->assertEquals($virtual, $response->headers->get('X-Accel-Redirect')); } + public function testDeleteFileAfterSend() + { + $request = Request::create('/'); + + $path = __DIR__.'/File/Fixtures/to_delete'; + touch($path); + $realPath = realpath($path); + $this->assertFileExists($realPath); + + $response = new BinaryFileResponse($realPath); + $response->deleteFileAfterSend(true); + + $response->prepare($request); + $response->sendContent(); + + $this->assertFileNotExists($path); + } + public function getSampleXAccelMappings() { return array( @@ -205,4 +223,12 @@ class BinaryFileResponseTest extends ResponseTestCase { return new BinaryFileResponse(__DIR__ . '/../README.md'); } + + public static function tearDownAfterClass() + { + $path = __DIR__.'/../Fixtures/to_delete'; + if (file_exists($path)) { + @unlink($path); + } + } }