From 3291ca8bce4c1f8de711b131e8e15b0f444e4f04 Mon Sep 17 00:00:00 2001 From: Andrey Knupp Vital Date: Tue, 22 Oct 2013 21:30:54 -0200 Subject: [PATCH 1/4] HttpMethod shouldn't instatiable --- lib/Unirest/HttpMethod.php | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/lib/Unirest/HttpMethod.php b/lib/Unirest/HttpMethod.php index d6b9c99..9aaec19 100644 --- a/lib/Unirest/HttpMethod.php +++ b/lib/Unirest/HttpMethod.php @@ -1,9 +1,15 @@ - Date: Tue, 22 Oct 2013 21:32:57 -0200 Subject: [PATCH 2/4] Improving is_hex function. --- lib/Unirest/Unirest.php | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/lib/Unirest/Unirest.php b/lib/Unirest/Unirest.php index e77f0d0..8c636ac 100644 --- a/lib/Unirest/Unirest.php +++ b/lib/Unirest/Unirest.php @@ -180,14 +180,10 @@ if (!function_exists('http_chunked_decode')) { /** * determine if a string can represent a number in hexadecimal - * + * @link http://uk1.php.net/ctype_xdigit * @param string $hex * @return boolean true if the string is a hex, otherwise false */ function is_hex($hex) { - // regex is for weenies - $hex = strtolower(trim(ltrim($hex,"0"))); - if (empty($hex)) { $hex = 0; }; - $dec = hexdec($hex); - return ($hex == dechex($dec)); + return ctype_xdigit($hex); } From 2842e30d52d44c1eda366b84369102add7bb772a Mon Sep 17 00:00:00 2001 From: Andrey Knupp Vital Date: Tue, 22 Oct 2013 21:40:46 -0200 Subject: [PATCH 3/4] Improve code indenting & others --- lib/Unirest/HttpResponse.php | 144 +++++++-------- lib/Unirest/Unirest.php | 349 +++++++++++++++++------------------ 2 files changed, 245 insertions(+), 248 deletions(-) diff --git a/lib/Unirest/HttpResponse.php b/lib/Unirest/HttpResponse.php index c076b7c..aa76f98 100644 --- a/lib/Unirest/HttpResponse.php +++ b/lib/Unirest/HttpResponse.php @@ -1,77 +1,77 @@ -code = $code; - $this->headers = $this->get_headers_from_curl_response($headers); - $this->raw_body = $raw_body; - $this->body = $raw_body; - $json = json_decode($raw_body); - if (json_last_error() == JSON_ERROR_NONE) { - $this->body = $json; - } - } + namespace Unirest; - /** - * Return a property of the response if it exists - * Possibilities include: - * - code - * - raw_body - * - body (if the response is json-decodable) - * - headers - * @param [type] $property [description] - * @return [type] [description] - */ - public function __get($property) - { - if (property_exists($this, $property)) { - return $this->$property; - } - } + class HttpResponse + { - /** - * Set the properties of this object - * @param string $property The property name - * @param mixed $value The property value - */ - public function __set($property, $value) - { - if (property_exists($this, $property)) { - $this->$property = $value; - } - return $this; - } - - /** - * Retrieve the cURL response headers from the - * header string and convert it into an array - * @param string $headers header string from cURL response - * @return array headers in array form - */ - private function get_headers_from_curl_response($headers) - { - $headers = explode("\r\n", $headers); - array_shift($headers); + private $code; + private $raw_body; + private $body; + private $headers; - foreach ($headers as $line) { - if (strstr($line, ': ')) { - list ($key, $value) = explode(': ', $line); - $result[$key] = $value; - } - } + /** + * @param int $code response code of the cURL request + * @param string $raw_body the raw body of the cURL response + * @param string $headers raw header string from cURL response + */ + public function __construct($code, $raw_body, $headers) + { + $this->code = $code; + $this->headers = $this->get_headers_from_curl_response($headers); + $this->raw_body = $raw_body; + $this->body = $raw_body; + $json = json_decode($raw_body); + + if (json_last_error() == JSON_ERROR_NONE) { + $this->body = $json; + } + } - return $result; - } -} + /** + * Return a property of the response if it exists. + * Possibilities include: code, raw_body, headers, body (if the response is json-decodable) + * @return mixed + */ + public function __get($property) + { + if (property_exists($this, $property)) { + return $this->$property; + } + } + + /** + * Set the properties of this object + * @param string $property the property name + * @param mixed $value the property value + */ + public function __set($property, $value) + { + if (property_exists($this, $property)) { + $this->$property = $value; + } + return $this; + } + + /** + * Retrieve the cURL response headers from the + * header string and convert it into an array + * @param string $headers header string from cURL response + * @return array + */ + private function get_headers_from_curl_response($headers) + { + $headers = explode("\r\n", $headers); + array_shift($headers); + + foreach ($headers as $line) { + if (strstr($line, ': ')) { + list ($key, $value) = explode(': ', $line); + $result[$key] = $value; + } + } + + return $result; + } + + } \ No newline at end of file diff --git a/lib/Unirest/Unirest.php b/lib/Unirest/Unirest.php index 8c636ac..e0352d8 100644 --- a/lib/Unirest/Unirest.php +++ b/lib/Unirest/Unirest.php @@ -1,189 +1,186 @@ $val) { - $key = trim(strtolower($key)); - if ($key == "user-agent" || $key == "expect") continue; - $lowercaseHeaders[] = $key . ": " . $val; - } - $lowercaseHeaders[] = "user-agent: unirest-php/1.0"; - $lowercaseHeaders[] = "expect:"; - - $ch = curl_init(); - if ($httpMethod != HttpMethod::GET) { - curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, $httpMethod); - curl_setopt ($ch, CURLOPT_POSTFIELDS, $body); - } - - curl_setopt ($ch, CURLOPT_URL , Unirest::encodeUrl($url)); - curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true); - curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true); - curl_setopt ($ch, CURLOPT_MAXREDIRS, 10); - curl_setopt ($ch, CURLOPT_HTTPHEADER, $lowercaseHeaders); - curl_setopt ($ch, CURLOPT_HEADER, true); - curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, false); - - $response = curl_exec($ch); - $error = curl_error($ch); - if ($error) { - throw new \Exception($error); - } - - // Split the full response in its headers and body - $curl_info = curl_getinfo($ch); - $header_size = $curl_info["header_size"]; - $header = substr($response, 0, $header_size); - $body = substr($response, $header_size); - $httpCode = $curl_info["http_code"]; - - return new HttpResponse($httpCode, $body, $header); - } - - /** - * Ensure that a URL is encoded and safe to use with cURL - * @param string $url URL to encode - * @return string Encoded URL - */ - private static function encodeUrl($url) - { - // Parse URL into pieces - $url_parsed = parse_url($url); + /** + * Send POST request to a URL + * @param string $url URL to send the POST request to + * @param array $headers additional headers to send + * @param mixed $body POST body data + * @return string|stdObj response string or stdObj if response is json-decodable + */ + public static function post($url, $headers = array(), $body = NULL) + { + return Unirest::request(HttpMethod::POST, $url, $body, $headers); + } - // Build the basics bypassing notices - $scheme = $url_parsed['scheme'] . '://'; - $host = $url_parsed['host']; - $port = (isset($url_parsed['port']) ? $url_parsed['port'] : null ); - $path = (isset($url_parsed['path']) ? $url_parsed['path'] : null ); - $query = (isset($url_parsed['query']) ? $url_parsed['query'] : null ); + /** + * Send DELETE request to a URL + * @param string $url URL to send the DELETE request to + * @param array $headers additional headers to send + * @return string|stdObj response string or stdObj if response is json-decodable + */ + public static function delete($url, $headers = array()) + { + return Unirest::request(HttpMethod::DELETE, $url, NULL, $headers); + } - // Do we need to encode anything? - if ($query != null) { - // Break up the query into an array - parse_str($url_parsed['query'], $query_parsed); - // Encode and build query based on RFC 1738 - $query = '?'.http_build_query($query_parsed); - } - - // Handle port seperator - if ($port && $port[0] != ":") - $port = ":" . $port; + /** + * Send PUT request to a URL + * @param string $url URL to send the PUT request to + * @param array $headers additional headers to send + * @param mixed $body PUT body data + * @return string|stdObj response string or stdObj if response is json-decodable + */ + public static function put($url, $headers = array(), $body = NULL) + { + return Unirest::request(HttpMethod::PUT, $url, $body, $headers); + } - // Return the completed URL - $result = $scheme . $host . $port . $path . $query; - return $result; - } - -} + /** + * Send PATCH request to a URL + * @param string $url URL to send the PATCH request to + * @param array $headers additional headers to send + * @param mixed $body PATCH body data + * @return string|stdObj response string or stdObj if response is json-decodable + */ + public static function patch($url, $headers = array(), $body = NULL) + { + return Unirest::request(HttpMethod::PATCH, $url, $body, $headers); + } -if (!function_exists('http_chunked_decode')) { - /** - * dechunk an http 'transfer-encoding: chunked' message - * - * @param string $chunk the encoded message - * @return string the decoded message. If $chunk wasn't encoded properly it will be returned unmodified. - */ - function http_chunked_decode($chunk) { - $pos = 0; - $len = strlen($chunk); - $dechunk = null; + /** + * Send a cURL request + * @param string $httpMethod HTTP method to use (based off \Unirest\HttpMethod constants) + * @param string $url URL to send the request to + * @param mixed $body request body + * @param array $headers additional headers to send + * @throws Exception if a cURL error occurs + * @return HttpResponse + */ + private static function request($httpMethod, $url, $body = NULL, $headers = array()) + { + $lowercaseHeaders = array(); + foreach ($headers as $key => $val) { + $key = trim(strtolower($key)); + if ($key == "user-agent" || $key == "expect") + continue; + $lowercaseHeaders[] = $key . ": " . $val; + } + $lowercaseHeaders[] = "user-agent: unirest-php/1.0"; + $lowercaseHeaders[] = "expect:"; - while(($pos < $len) - && ($chunkLenHex = substr($chunk,$pos, ($newlineAt = strpos($chunk,"\n",$pos+1))-$pos)) - ) { - if (!is_hex($chunkLenHex)) { - trigger_error('Value is not properly chunk encoded', E_USER_WARNING); - return $chunk; - } + $ch = curl_init(); + if ($httpMethod != HttpMethod::GET) { + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $httpMethod); + curl_setopt($ch, CURLOPT_POSTFIELDS, $body); + } + + curl_setopt($ch, CURLOPT_URL, Unirest::encodeUrl($url)); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); + curl_setopt($ch, CURLOPT_MAXREDIRS, 10); + curl_setopt($ch, CURLOPT_HTTPHEADER, $lowercaseHeaders); + curl_setopt($ch, CURLOPT_HEADER, true); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + + $response = curl_exec($ch); + $error = curl_error($ch); + if ($error) { + throw new \Exception($error); + } + + $curl_info = curl_getinfo($ch); + $header_size = $curl_info["header_size"]; + $header = substr($response, 0, $header_size); + $body = substr($response, $header_size); + $httpCode = $curl_info["http_code"]; + + return new HttpResponse($httpCode, $body, $header); + } + + /** + * Ensure that a URL is encoded and safe to use with cURL + * @param string $url URL to encode + * @return string + */ + private static function encodeUrl($url) + { + $url_parsed = parse_url($url); + + $scheme = $url_parsed['scheme'] . '://'; + $host = $url_parsed['host']; + $port = (isset($url_parsed['port']) ? $url_parsed['port'] : null); + $path = (isset($url_parsed['path']) ? $url_parsed['path'] : null); + $query = (isset($url_parsed['query']) ? $url_parsed['query'] : null); + + if ($query != null) { + parse_str($url_parsed['query'], $query_parsed); + $query = '?' . http_build_query($query_parsed); + } + + if ($port && $port[0] != ":") + $port = ":" . $port; + + $result = $scheme . $host . $port . $path . $query; + return $result; + } - $pos = $newlineAt + 1; - $chunkLen = hexdec(rtrim($chunkLenHex,"\r\n")); - $dechunk .= substr($chunk, $pos, $chunkLen); - $pos = strpos($chunk, "\n", $pos + $chunkLen) + 1; - } - return $dechunk; } -} -/** - * determine if a string can represent a number in hexadecimal - * @link http://uk1.php.net/ctype_xdigit - * @param string $hex - * @return boolean true if the string is a hex, otherwise false - */ -function is_hex($hex) { - return ctype_xdigit($hex); -} + if (!function_exists('http_chunked_decode')) { + /** + * Dechunk an http 'transfer-encoding: chunked' message + * @param string $chunk the encoded message + * @return string the decoded message + */ + function http_chunked_decode($chunk) + { + $pos = 0; + $len = strlen($chunk); + $dechunk = null; + + while (($pos < $len) + && ($chunkLenHex = substr($chunk, $pos, ($newlineAt = strpos($chunk, "\n", $pos + 1)) - $pos))) { + + if (!is_hex($chunkLenHex)) { + trigger_error('Value is not properly chunk encoded', E_USER_WARNING); + return $chunk; + } + + $pos = $newlineAt + 1; + $chunkLen = hexdec(rtrim($chunkLenHex, "\r\n")); + $dechunk .= substr($chunk, $pos, $chunkLen); + $pos = strpos($chunk, "\n", $pos + $chunkLen) + 1; + } + + return $dechunk; + } + } + + /** + * determine if a string can represent a number in hexadecimal + * @link http://uk1.php.net/ctype_xdigit + * @param string $hex + * @return boolean true if the string is a hex, otherwise false + */ + function is_hex($hex) + { + return ctype_xdigit($hex); + } + \ No newline at end of file From a8418500cb194f5be6da6c3879791a38bc3c2830 Mon Sep 17 00:00:00 2001 From: scottmotte Date: Fri, 1 Nov 2013 13:52:24 -0700 Subject: [PATCH 4/4] More detailed install instructions in README. Also make composer the priority install. --- README.md | 38 +++++++++++++++++--------------------- 1 file changed, 17 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 509f499..099268c 100644 --- a/README.md +++ b/README.md @@ -4,39 +4,35 @@ Unirest is a set of lightweight HTTP libraries available in multiple languages. Created with love by http://mashape.com - - -### Installing -Unirest-PHP requires PHP `v5.3+`. Download the PHP library from Github, and require in your script like so: - -```php -require_once './lib/Unirest.php'; -``` - -### Using Composer - -[Composer](http://getcomposer.org/) is a package manager for PHP. - -In the composer.json file in your project add: +### Install with Composer +If you're using [Composer](https://github.com/composer/composer) to manage +dependencies, you can add Unirest with it. ```javascript { "require" : { "mashape/unirest-php" : "dev-master" + }, + "autoload": { + "psr-0": {"Unirest": "lib/"} } } ``` -And then run: -``` -php composer.phar install +### Install source from GitHub +Unirest-PHP requires PHP `v5.3+`. Download the PHP library from Github, and require in your script like so: + +To install the source code: + +```bash +$ git clone git@github.com:Mashape/unirest-php.git ``` -Include the library in your project with: +And include it in your scripts: -```php -require 'vendor/autoload.php'; -```` +```bash +require_once '/path/to/unirest-php/lib/Unirest.php'; +``` ## Creating Request So you're probably wondering how using Unirest makes creating requests in PHP easier, let's look at a working example: