From 1504e81ff11562b9cdda6ac57c4902e63628bbe6 Mon Sep 17 00:00:00 2001 From: thefosk Date: Wed, 8 Jan 2014 19:05:22 -0800 Subject: [PATCH] supporting curl_file_create` --- README.md | 4 +++- lib/Unirest/Unirest.php | 12 ++++++++++++ test/Unirest/UnirestTest.php | 2 +- 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 2a974f1..530df99 100644 --- a/README.md +++ b/README.md @@ -71,10 +71,12 @@ To upload files in a multipart form representation simply place an `@` symbol be ```php $response = Unirest::post("http://httpbin.org/post", array( "Accept" => "application/json" ), array( - "file" => "@/tmp/file.txt" + "file" => Unirest::file("/tmp/file.txt") ) ); ``` + + Use the value of `Unirest::file($path)` to assign a file to a parameter. ### Custom Entity Body Sending a custom body such as a JSON Object rather than a string or form style parameters we utilize json_encode for the body: diff --git a/lib/Unirest/Unirest.php b/lib/Unirest/Unirest.php index b32fefe..ef3fbf2 100644 --- a/lib/Unirest/Unirest.php +++ b/lib/Unirest/Unirest.php @@ -113,6 +113,18 @@ return Unirest::request(HttpMethod::PATCH, $url, $body, $headers, $username, $password); } + /** + * Prepares a file for upload. To be used inside the parameters declaration for a request. + * @param string $path The file path + */ + public static function file($path) { + if (function_exists("curl_file_create")) { + return curl_file_create($path); + } else { + return "@" . $path; + } + } + /** * This function is useful for serializing multidimensional arrays, and avoid getting * the "Array to string conversion" notice diff --git a/test/Unirest/UnirestTest.php b/test/Unirest/UnirestTest.php index c9d19aa..e6eca2b 100644 --- a/test/Unirest/UnirestTest.php +++ b/test/Unirest/UnirestTest.php @@ -94,7 +94,7 @@ class UnirestTest extends UnitTestCase $response = Unirest::post("http://httpbin.org/post", array( "Accept" => "application/json" ), array( "name" => "Mark", - "file" => "@" . dirname(__FILE__) . "/test_upload.txt" + "file" => Unirest::file(dirname(__FILE__) . "/test_upload.txt") ) ); $this->assertEqual(200, $response->code);