Skip to content

Commit

Permalink
Do not write file uploads to files, keep in memory
Browse files Browse the repository at this point in the history
  • Loading branch information
onigoetz committed Jul 28, 2015
1 parent 8213ff5 commit 5bea2e7
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 8 deletions.
20 changes: 15 additions & 5 deletions src/MultipartParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down
9 changes: 6 additions & 3 deletions tests/MultipartParserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
];
Expand Down

0 comments on commit 5bea2e7

Please sign in to comment.