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

Feature upload #567

Open
wants to merge 7 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
8 changes: 8 additions & 0 deletions docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,14 @@ $data = array('some' => 'data');
$response = WpOrg\Requests\Requests::post($url, $headers, json_encode($data));
```

To send a file as part of a post body:

```php
$url = 'https://api.github.com/some/endpoint';
$body = \WpOrg\Requests\Requests::add_files_to_body( array('mydata' => 'something'), $file_path, 'file1' );
$response = WpOrg\Requests\Requests::post( $url, $headers, $body );
```

Note that if you don't manually specify a Content-Type header, Requests has
undefined behaviour for the header. It may be set to various values depending
on the internal execution path, so it's recommended to set this explicitly if
Expand Down
9 changes: 9 additions & 0 deletions examples/post.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,12 @@

// Check what we received
var_dump($request);
// create temp file for example
file_put_contents( $tmpfile = tempnam(sys_get_temp_dir(), 'requests' ), 'hello');

// Now let's make a request!
$body = \WpOrg\Requests\Requests::add_files_to_body( array('mydata' => 'something'), $tmpfile, 'file1' );
$request = WpOrg\Requests\Requests::post('http://httpbin.org/post', array(), $body );

// Check what we received
var_dump($request);
6 changes: 6 additions & 0 deletions src/Exception/RequestsExceptionFile.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?php
namespace WpOrg\Requests\Exception;

use WpOrg\Requests\Exception;

class RequestsExceptionFile extends Exception {}
45 changes: 38 additions & 7 deletions src/Requests.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
use WpOrg\Requests\Response;
use WpOrg\Requests\Transport\Curl;
use WpOrg\Requests\Transport\Fsockopen;
use WpOrg\Requests\Utility\RequestsFile;

/**
* Requests for PHP
Expand Down Expand Up @@ -248,6 +249,33 @@ protected static function get_transport($capabilities = array()) {
return new $class();
}


/**
* @param array|string $body
* @param array|string $key_files
* @param string $file_key
*
* @return array $body
*/
public static function add_files_to_body( $body, $key_files, $file_key = '' ) {
if ( ! is_array( $body ) ) {
if ( is_scalar( $body ) && ! empty( $body ) ) {
$body = array( $body );
} else {
$body = array();
}
}
if ( is_array( $key_files ) ) {
foreach ($key_files as $key => $file_path ){
$body[ $key ] = new RequestsFile( $file_path );
}
} elseif( is_scalar( $file_key ) && ! empty( $key_files ) ) {
$body[ $file_key ] = new RequestsFile( $key_files );
}

return $body;
}

/**#@+
* @see \WpOrg\Requests\Requests::request()
* @param string $url
Expand Down Expand Up @@ -562,15 +590,16 @@ public static function set_certificate_path($path) {
self::$certificate_path = $path;
}


/**
* Set the default values
* @param $url
* @param $headers
* @param $data
* @param $type
* @param $options
*
* @param string $url URL to request
* @param array $headers Extra headers to send with the request
* @param array|null $data Data to send either as a query string for GET/HEAD requests, or in the body for POST requests
* @param string $type HTTP request type
* @param array $options Options for the request
* @return array $options
* @return mixed
* @throws \WpOrg\Requests\Exception
*/
protected static function set_defaults(&$url, &$headers, &$data, &$type, &$options) {
if (!preg_match('/^http(s)?:\/\//i', $url, $matches)) {
Expand Down Expand Up @@ -622,6 +651,8 @@ protected static function set_defaults(&$url, &$headers, &$data, &$type, &$optio
$options['data_format'] = 'body';
}
}

return $options;
}

/**
Expand Down
26 changes: 23 additions & 3 deletions src/Transport/Curl.php
Original file line number Diff line number Diff line change
Expand Up @@ -359,15 +359,35 @@ private 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();
}
elseif (!is_string($data)) {
$data = http_build_query($data, '', '&');
}

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);
}
}
else {
foreach($files as $key => $file) {
$data[$key] = "@{$file->path}";
}
}
}

Expand Down
39 changes: 38 additions & 1 deletion src/Transport/Fsockopen.php
Original file line number Diff line number Diff line change
Expand Up @@ -176,8 +176,18 @@ 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)) {
$request_body = http_build_query($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;
Expand All @@ -194,6 +204,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
74 changes: 74 additions & 0 deletions src/Utility/RequestsFile.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?php
/**
* File handler for file uploads
*
* @package Requests
* @subpackage Utilities
*/

namespace WpOrg\Requests\Utility;


use WpOrg\Requests\Exception\RequestsExceptionFile;
/**
* A file object describing an upload.
*
* Used in the $data parameter to POST requests.
*
* @package Requests
* @subpackage Utilities
*/
class RequestsFile {
/**
* 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.
*
* @return RequestsFile
*@throws RequestsExceptionFile If file is not readable or does not exist.
*
*/
public function __construct($path, $type = null, $name = null) {
if (!file_exists($path) || !is_readable($path)) {
throw new RequestsExceptionFile('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);
}
}
Loading