From 5bea2e703822b46c2b0872535eb5e1b8974a6fd2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ste=CC=81phane=20Goetz?= Date: Tue, 28 Jul 2015 22:52:47 +0200 Subject: [PATCH] Do not write file uploads to files, keep in memory --- src/MultipartParser.php | 20 +++++++++++++++----- tests/MultipartParserTest.php | 9 ++++++--- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/src/MultipartParser.php b/src/MultipartParser.php index 681bf231..d4c0f4b9 100644 --- a/src/MultipartParser.php +++ b/src/MultipartParser.php @@ -142,17 +142,27 @@ protected function file($string) $content = preg_replace('/Content-Type: (.*)[^\n\r]/', '', $match[3]); $content = ltrim($content, "\r\n"); - $path = tempnam(sys_get_temp_dir(), "php"); - $err = file_put_contents($path, $content); + // Put content in a stream + $stream = fopen('php://memory', 'r+'); + if ($content !== '') { + fwrite($stream, $content); + fseek($stream, 0); + } $data = [ 'name' => $match[2], 'type' => trim($mime[1]), - 'tmp_name' => $path, - 'error' => ($err === false) ? UPLOAD_ERR_NO_FILE : UPLOAD_ERR_OK, - 'size' => filesize($path), + 'stream' => $stream, // Instead of writing to a file, we write to a stream. + 'error' => UPLOAD_ERR_OK, + 'size' => function_exists('mb_strlen')? mb_strlen($content, '8bit') : strlen($content), ]; + //TODO :: have an option to write to files to emulate the same functionality as a real php server + //$path = tempnam(sys_get_temp_dir(), "php"); + //$err = file_put_contents($path, $content); + //$data['tmp_name'] = $path; + //$data['error'] = ($err === false) ? UPLOAD_ERR_NO_FILE : UPLOAD_ERR_OK; + $this->addResolved('files', $match[1], $data); } diff --git a/tests/MultipartParserTest.php b/tests/MultipartParserTest.php index 0bffd5c3..39a02c71 100644 --- a/tests/MultipartParserTest.php +++ b/tests/MultipartParserTest.php @@ -83,13 +83,16 @@ public function testFileUpload() { $uploaded_blank = $parser->getFiles()['files'][0]; - $this->assertEquals($file, file_get_contents($uploaded_blank['tmp_name'])); + // The original test was `file_get_contents($uploaded_blank['tmp_name'])` + // but as we moved to resources, we can't use that anymore, this is the only + // difference with a stock php implementation + $this->assertEquals($file, stream_get_contents($uploaded_blank['stream'])); - $uploaded_blank['tmp_name'] = 'file'; //override the filename as it is random + $uploaded_blank['stream'] = 'file'; //override the resource as it is random $expected_file = [ 'name' => 'blank.gif', 'type' => 'image/gif', - 'tmp_name' => 'file', + 'stream' => 'file', 'error' => 0, 'size' => 43, ];