Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

File uploads #313

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions library/Requests/Exception/File.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?php

class Requests_Exception_File extends Requests_Exception {

}
70 changes: 70 additions & 0 deletions library/Requests/File.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?php
/**
* File handler for file uploads
*
* @package Requests
* @subpackage Utilities
*/

/**
* A file object describing an upload.
*
* Used in the $data parameter to POST requests.
*
* @package Requests
* @subpackage Utilities
*/
class Requests_File {
/**
* The path to the file.
*
* @var string|null
*/
public $path = null;

/**
* The file mimetype.
*
* @var string|null
*/
public $type = null;

/**
* Override the file name when uploading.
*
* @var string|null
*/
public $name = null;

/**
* Create a file wrapper.
*
* @param string $filepath The path to the file.
* @param string $mimetype The mimetype override. Will try to guess if not given.
* @param string $filename The upload file name.
*
* @throws Requests_Exception_File If file is not readable or does not exist.
*
* @return Requests_File
*/
public function __construct($path, $type = null, $name = null) {
if (!file_exists($path) || !is_readable($path)) {
throw new Requests_Exception_File('File is not readable', null, $path);
}

$this->path = $path;
$this->type = $type ? $type : mime_content_type($path);
$this->name = $name ? $name : basename($path);
}

/**
* Retrieve the contents into a string.
*
* Caution: large files will fill up the RAM.
*
* @return string The contents.
*/
public function get_contents() {
return file_get_contents($this->path);
}
}
26 changes: 23 additions & 3 deletions library/Requests/Transport/cURL.php
Original file line number Diff line number Diff line change
Expand Up @@ -316,15 +316,35 @@ protected function setup_handle($url, $headers, $data, $options) {

$headers = Requests::flatten($headers);

$files = array();

if (!empty($data)) {
$data_format = $options['data_format'];

if (is_array($data)) {
foreach($data as $key => $value) {
if ($value instanceof Requests_File) {
$files[$key] = $value;
}
}
}

if ($data_format === 'query') {
$url = self::format_get($url, $data);
$data = '';
$data = array();
}
}

if (!empty($files)) {
if (function_exists('curl_file_create')) {
foreach($files as $key => $file) {
$data[$key] = curl_file_create($file->path, $file->type, $file->name);
}
}
elseif (!is_string($data)) {
$data = http_build_query($data, null, '&');
else {
foreach($files as $key => $file) {
$data[$key] = "@{$file->path}";
}
}
}

Expand Down
39 changes: 38 additions & 1 deletion library/Requests/Transport/fsockopen.php
Original file line number Diff line number Diff line change
Expand Up @@ -153,14 +153,24 @@ public function request($url, $headers = array(), $data = array(), $options = ar
$out = sprintf("%s %s HTTP/%.1f\r\n", $options['type'], $path, $options['protocol_version']);

if ($options['type'] !== Requests::TRACE) {
$files = array();

if (is_array($data)) {
foreach($data as $key => $value) {
if ($value instanceof Requests_File) {
$files[$key] = $value;
}
}
}

if (is_array($data) && empty($files)) {
$request_body = http_build_query($data, null, '&');
}
else {
$request_body = $data;
}

if (!empty($data)) {
if (!empty($data) && empty($files)) {
if (!isset($case_insensitive_headers['Content-Length'])) {
$headers['Content-Length'] = strlen($request_body);
}
Expand All @@ -169,6 +179,33 @@ public function request($url, $headers = array(), $data = array(), $options = ar
$headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
}
}

if (!empty($files)) {
$boundary = sha1(time());
$headers['Content-Type'] = "multipart/form-data; boundary=$boundary";

$request_body = '';

if (!empty($data)) {
foreach ($data as $key => $value) {
$request_body .= "--$boundary\r\n";

if ($value instanceof Requests_File) {
$request_body .= "Content-Disposition: form-data; name=\"$key\"; filename=\"$value->name\"\r\n";
$request_body .= "Content-Type: $value->type";
$request_body .= "\r\n\r\n" . $value->get_contents() . "\r\n";
}
else {
$request_body .= "Content-Disposition: form-data; name=\"$key\"";
$request_body .= "\r\n\r\n" . $value . "\r\n";
}
}
}

$request_body .= "--$boundary--\r\n\r\n";

$headers['Content-Length'] = strlen($request_body);
}
}

if (!isset($case_insensitive_headers['Host'])) {
Expand Down
39 changes: 39 additions & 0 deletions tests/File.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

class RequestsTest_File extends PHPUnit_Framework_TestCase {
/**
* @expectedException Requests_Exception_File
*/
public function testInvalidFile() {
new Requests_File(sys_get_temp_dir() . 'null.exe');
}

public function testBasic() {
file_put_contents($tmpfile = tempnam(sys_get_temp_dir(), 'requests'), '');
$file = new Requests_File($tmpfile, 'text/plain', 'readme.txt');

$this->assertEquals($file->path, $tmpfile);
$this->assertEquals($file->type, 'text/plain');
$this->assertEquals($file->name, 'readme.txt');

file_put_contents($tmpfile = tempnam(sys_get_temp_dir(), 'requests'), 'hello');
$file = new Requests_File($tmpfile);
$this->assertEquals($file->name, basename($tmpfile));

$this->assertEquals($file->get_contents(), 'hello');
}

public function testMime() {
file_put_contents($tmpfile = tempnam(sys_get_temp_dir(), 'requests'), 'hello');
$file = new Requests_File($tmpfile);
$this->assertEquals($file->type, 'text/plain');

file_put_contents($tmpfile = tempnam(sys_get_temp_dir(), 'requests'), "\xff\xd8\xff");
$file = new Requests_File($tmpfile);
$this->assertEquals($file->type, 'image/jpeg');

file_put_contents($tmpfile = tempnam(sys_get_temp_dir(), 'requests'), "\x78\x01");
$file = new Requests_File($tmpfile);
$this->assertEquals($file->type, 'application/octet-stream');
}
}
9 changes: 9 additions & 0 deletions tests/Transport/Base.php
Original file line number Diff line number Diff line change
Expand Up @@ -845,4 +845,13 @@ public function testBodyDataFormat() {
$this->assertEquals(httpbin('/post'), $result['url']);
$this->assertEquals(array('test' => 'true', 'test2' => 'test'), $result['form']);
}

public function testFileUploads() {
file_put_contents($tmpfile = tempnam(sys_get_temp_dir(), 'requests'), 'some secret bytes, yo');
$request = Requests::post('http://httpbin.org/post', array(), array('foo' => 'bar', 'file1' => new Requests_File($tmpfile)), $this->getOptions());

$result = json_decode($request->body, true);
$this->assertEquals($result['files']['file1'], 'some secret bytes, yo');
$this->assertEquals($result['form']['foo'], 'bar');
}
}
1 change: 1 addition & 0 deletions tests/phpunit.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
<testsuite name="General">
<file>ChunkedEncoding.php</file>
<file>Cookies.php</file>
<file>File.php</file>
<file>IDNAEncoder.php</file>
<file>IRI.php</file>
<file>Requests.php</file>
Expand Down