Skip to content

Commit 4ddb00d

Browse files
[HttpFoundation] Added a switch to delete file after the response is send
1 parent 6b3bf91 commit 4ddb00d

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

BinaryFileResponse.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ class BinaryFileResponse extends Response
3030
protected $file;
3131
protected $offset;
3232
protected $maxlen;
33+
protected $deleteFileAfterSend = false;
3334

3435
/**
3536
* Constructor.
@@ -258,6 +259,10 @@ public function sendContent()
258259

259260
fclose($out);
260261
fclose($file);
262+
263+
if ($this->deleteFileAfterSend) {
264+
unlink($this->file->getPathname());
265+
}
261266
}
262267

263268
/**
@@ -289,4 +294,19 @@ public static function trustXSendfileTypeHeader()
289294
{
290295
self::$trustXSendfileTypeHeader = true;
291296
}
297+
298+
/**
299+
* If this is set to true, the file will be unlinked after the request is send
300+
* Note: If the X-Sendfile header is used, the deleteFileAfterSend setting will not be used.
301+
* @param bool $shouldDelete
302+
*
303+
* @return BinaryFileResponse
304+
*/
305+
public function deleteFileAfterSend($shouldDelete)
306+
{
307+
$this->deleteFileAfterSend = $shouldDelete;
308+
309+
return $this;
310+
}
311+
292312
}

Tests/BinaryFileResponseTest.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,24 @@ public function testXAccelMapping($realpath, $mapping, $virtual)
203203
$this->assertEquals($virtual, $response->headers->get('X-Accel-Redirect'));
204204
}
205205

206+
public function testDeleteFileAfterSend()
207+
{
208+
$request = Request::create('/');
209+
210+
$path = __DIR__.'/File/Fixtures/to_delete';
211+
touch($path);
212+
$realPath = realpath($path);
213+
$this->assertFileExists($realPath);
214+
215+
$response = new BinaryFileResponse($realPath);
216+
$response->deleteFileAfterSend(true);
217+
218+
$response->prepare($request);
219+
$response->sendContent();
220+
221+
$this->assertFileNotExists($path);
222+
}
223+
206224
public function getSampleXAccelMappings()
207225
{
208226
return array(
@@ -215,4 +233,12 @@ protected function provideResponse()
215233
{
216234
return new BinaryFileResponse(__DIR__ . '/../README.md');
217235
}
236+
237+
public static function tearDownAfterClass()
238+
{
239+
$path = __DIR__.'/../Fixtures/to_delete';
240+
if (file_exists($path)) {
241+
@unlink($path);
242+
}
243+
}
218244
}

0 commit comments

Comments
 (0)