.github
1 year ago
.phan
1 year ago
src
1 year ago
tests
1 year ago
.editorconfig
1 year ago
LICENSE
1 year ago
README.md
1 year ago
composer.json
1 year ago
composer.lock
1 year ago
phpcs-ruleset.xml
1 year ago
phpunit.xml
1 year ago
README.md
440 lines
| 1 | # Unirest for PHP |
| 2 | |
| 3 | [![version][packagist-version]][packagist-url] |
| 4 | [![Downloads][packagist-downloads]][packagist-url] |
| 5 | [](https://github.com/apimatic/unirest-php/actions/workflows/php.yml](https://github.com/apimatic/unirest-php/actions/workflows/php.yml](https://github.com/apimatic/unirest-php/actions/workflows/php.yml) |
| 6 | [![License][packagist-license]][license-url] |
| 7 | |
| 8 | Unirest is a set of lightweight HTTP libraries available in [](http://unirest.iomultiple languages](http://unirest.io](http://unirest.io). |
| 9 | |
| 10 | This fork is maintained by [](https://www.apimatic.ioAPIMatic](https://www.apimatic.io](https://www.apimatic.io) for its Code Generator as a Service. |
| 11 | |
| 12 | ## Features |
| 13 | |
| 14 | * Request class to create custom requests |
| 15 | * Simple HttpClientInterface to execute a Request |
| 16 | * Automatic JSON parsing into a native object for JSON responses |
| 17 | * Response data class to store http response information |
| 18 | * Supports form parameters, file uploads and custom body entities |
| 19 | * Supports gzip |
| 20 | * Supports Basic, Digest, Negotiate, NTLM Authentication natively |
| 21 | * Configuration class manage all the HttpClient's configurations |
| 22 | * Customizable timeout |
| 23 | * Customizable retries and backoff |
| 24 | * Customizable default headers for every request (DRY) |
| 25 | |
| 26 | ## Supported PHP Versions |
| 27 | - PHP 7.2 |
| 28 | - PHP 7.4 |
| 29 | - PHP 8.0 |
| 30 | - PHP 8.1 |
| 31 | - PHP 8.2 |
| 32 | |
| 33 | ## Installation |
| 34 | |
| 35 | To install `apimatic/unirest-php` with Composer, just add the following to your `composer.json` file: |
| 36 | |
| 37 | ```json |
| 38 | { |
| 39 | "require": { |
| 40 | "apimatic/unirest-php": "^4.0.0" |
| 41 | } |
| 42 | } |
| 43 | ``` |
| 44 | |
| 45 | or by running the following command: |
| 46 | |
| 47 | ```shell |
| 48 | composer require apimatic/unirest-php |
| 49 | ``` |
| 50 | |
| 51 | ## Usage |
| 52 | |
| 53 | ### Creating a HttpClient with Default Configurations |
| 54 | You can create a variable at class level and instantiate it with an instance of `HttpClient`, like: |
| 55 | |
| 56 | ```php |
| 57 | private $httpClient = new \Unirest\HttpClient(); |
| 58 | ``` |
| 59 | |
| 60 | ### Creating a HttpClient with Custom Configurations |
| 61 | To create a client with custom configurations you first required an instance of `Configuration`, and then add it to the HttpClient during its initialization, like: |
| 62 | ```php |
| 63 | $configurations = \Unirest\Configuration::init() |
| 64 | ->timeout(10) |
| 65 | ->enableRetries(true) |
| 66 | ->retryInterval(2.5); |
| 67 | $httpClient = new \Unirest\HttpClient($configurations); |
| 68 | ``` |
| 69 | This `Configuration` instance can further be customized by setting properties like: `maximumRetryWaitTime`, `verifyPeer`, `defaultHeaders`, etc. Check out [](#advanced-configurationAdvanced Configuration](#advanced-configuration](#advanced-configuration) for more information. |
| 70 | |
| 71 | ### Creating a Request |
| 72 | After the initialization of HttpClient, you will be needing an instance of `Request` that is required to be exchanged as `Response`. |
| 73 | ```php |
| 74 | $request = new \Unirest\Request\Request( |
| 75 | 'http://mockbin.com/request', |
| 76 | RequestMethod::GET, |
| 77 | ['headerKey' => 'headerValue'], |
| 78 | Unirest\Request\Body::json(["key" => "value"]'), |
| 79 | RetryOption::ENABLE_RETRY |
| 80 | ); |
| 81 | ``` |
| 82 | Let's look at a working example of sending the above request: |
| 83 | |
| 84 | ```php |
| 85 | $headers = array('Accept' => 'application/json'); |
| 86 | $query = array('foo' => 'hello', 'bar' => 'world'); |
| 87 | |
| 88 | $response = $this->httpClient->execute($request); |
| 89 | |
| 90 | $response->getStatusCode(); // HTTP Status code |
| 91 | $response->getHeaders(); // Headers |
| 92 | $response->getBody(); // Parsed body |
| 93 | $response->getRawBody(); // Unparsed body |
| 94 | ``` |
| 95 | |
| 96 | ### JSON Requests *(`application/json`)* |
| 97 | |
| 98 | A JSON Request can be constructed using the `Unirest\Request\Body::Json` helper: |
| 99 | |
| 100 | ```php |
| 101 | $headers = array('Accept' => 'application/json'); |
| 102 | $data = array('name' => 'ahmad', 'company' => 'mashape'); |
| 103 | |
| 104 | $body = Unirest\Request\Body::Json($data); |
| 105 | $request = new \Unirest\Request\Request( |
| 106 | 'http://mockbin.com/request', |
| 107 | RequestMethod::POST, |
| 108 | $headers, |
| 109 | $body |
| 110 | ); |
| 111 | $response = $this->httpClient->execute($request); |
| 112 | ``` |
| 113 | |
| 114 | **Notes:** |
| 115 | - `Content-Type` headers will be automatically set to `application/json` |
| 116 | - the data variable will be processed through [`json_encode`](http://php.net/manual/en/function.json-encode.php) with default values for arguments. |
| 117 | - an error will be thrown if the [JSON Extension](http://php.net/manual/en/book.json.php) is not available. |
| 118 | |
| 119 | ### Form Requests *(`application/x-www-form-urlencoded`)* |
| 120 | |
| 121 | A typical Form Request can be constructed using the `Unirest\Request\Body::Form` helper: |
| 122 | |
| 123 | ```php |
| 124 | $headers = array('Accept' => 'application/json'); |
| 125 | $data = array('name' => 'ahmad', 'company' => 'mashape'); |
| 126 | |
| 127 | $body = Unirest\Request\Body::Form($data); |
| 128 | $request = new \Unirest\Request\Request( |
| 129 | 'http://mockbin.com/request', |
| 130 | RequestMethod::POST, |
| 131 | $headers, |
| 132 | $body |
| 133 | ); |
| 134 | $response = $this->httpClient->execute($request); |
| 135 | ``` |
| 136 | |
| 137 | **Notes:** |
| 138 | - `Content-Type` headers will be automatically set to `application/x-www-form-urlencoded` |
| 139 | - the final data array will be processed through [`http_build_query`](http://php.net/manual/en/function.http-build-query.php) with default values for arguments. |
| 140 | |
| 141 | ### Multipart Requests *(`multipart/form-data`)* |
| 142 | |
| 143 | A Multipart Request can be constructed using the `Unirest\Request\Body::Multipart` helper: |
| 144 | |
| 145 | ```php |
| 146 | $headers = array('Accept' => 'application/json'); |
| 147 | $data = array('name' => 'ahmad', 'company' => 'mashape'); |
| 148 | |
| 149 | $body = Unirest\Request\Body::Multipart($data); |
| 150 | $request = new \Unirest\Request\Request( |
| 151 | 'http://mockbin.com/request', |
| 152 | RequestMethod::POST, |
| 153 | $headers, |
| 154 | $body |
| 155 | ); |
| 156 | $response = $this->httpClient->execute($request); |
| 157 | ``` |
| 158 | |
| 159 | **Notes:** |
| 160 | |
| 161 | - `Content-Type` headers will be automatically set to `multipart/form-data`. |
| 162 | - an auto-generated `--boundary` will be set. |
| 163 | |
| 164 | ### Multipart File Upload |
| 165 | |
| 166 | simply add an array of files as the second argument to to the `Multipart` helper: |
| 167 | |
| 168 | ```php |
| 169 | $headers = array('Accept' => 'application/json'); |
| 170 | $data = array('name' => 'ahmad', 'company' => 'mashape'); |
| 171 | $files = array('bio' => '/path/to/bio.txt', 'avatar' => '/path/to/avatar.jpg'); |
| 172 | |
| 173 | $body = Unirest\Request\Body::Multipart($data, $files); |
| 174 | $request = new \Unirest\Request\Request( |
| 175 | 'http://mockbin.com/request', |
| 176 | RequestMethod::POST, |
| 177 | $headers, |
| 178 | $body |
| 179 | ); |
| 180 | $response = $this->httpClient->execute($request); |
| 181 | ``` |
| 182 | |
| 183 | If you wish to further customize the properties of files uploaded you can do so with the `Unirest\Request\Body::File` helper: |
| 184 | |
| 185 | ```php |
| 186 | $headers = array('Accept' => 'application/json'); |
| 187 | $body = array( |
| 188 | 'name' => 'ahmad', |
| 189 | 'company' => 'mashape' |
| 190 | 'bio' => Unirest\Request\Body::File('/path/to/bio.txt', 'text/plain'), |
| 191 | 'avatar' => Unirest\Request\Body::File('/path/to/my_avatar.jpg', 'text/plain', 'avatar.jpg') |
| 192 | ); |
| 193 | $request = new \Unirest\Request\Request( |
| 194 | 'http://mockbin.com/request', |
| 195 | RequestMethod::POST, |
| 196 | $headers, |
| 197 | $body |
| 198 | ); |
| 199 | $response = $this->httpClient->execute($request); |
| 200 | ``` |
| 201 | |
| 202 | **Note**: we did not use the `Unirest\Request\Body::multipart` helper in this example, it is not needed when manually adding files. |
| 203 | |
| 204 | ### Custom Body |
| 205 | |
| 206 | Sending a custom body such rather than using the `Unirest\Request\Body` helpers is also possible, for example, using a [`serialize`](http://php.net/manual/en/function.serialize.php) body string with a custom `Content-Type`: |
| 207 | |
| 208 | ```php |
| 209 | $headers = array('Accept' => 'application/json', 'Content-Type' => 'application/x-php-serialized'); |
| 210 | $body = serialize((array('foo' => 'hello', 'bar' => 'world')); |
| 211 | $request = new \Unirest\Request\Request( |
| 212 | 'http://mockbin.com/request', |
| 213 | RequestMethod::POST, |
| 214 | $headers, |
| 215 | $body |
| 216 | ); |
| 217 | $response = $this->httpClient->execute($request); |
| 218 | ``` |
| 219 | |
| 220 | ### Authentication |
| 221 | For Authentication you need httpClient instance with custom configurations, So, create `Configuration` instance like: |
| 222 | |
| 223 | ```php |
| 224 | // Basic auth |
| 225 | $configuration = Configuration::init() |
| 226 | ->auth('username', 'password', CURLAUTH_BASIC); |
| 227 | ``` |
| 228 | |
| 229 | The third parameter, which is a bitmask, will Unirest which HTTP authentication method(s) you want it to use for your proxy authentication. |
| 230 | |
| 231 | If more than one bit is set, Unirest *(at PHP's libcurl level)* will first query the site to see what authentication methods it supports and then pick the best one you allow it to use. *For some methods, this will induce an extra network round-trip.* |
| 232 | |
| 233 | **Supported Methods** |
| 234 | |
| 235 | | Method | Description | |
| 236 | | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |
| 237 | | `CURLAUTH_BASIC` | HTTP Basic authentication. This is the default choice | |
| 238 | | `CURLAUTH_DIGEST` | HTTP Digest authentication. as defined in [RFC 2617](http://www.ietf.org/rfc/rfc2617.txt) | |
| 239 | | `CURLAUTH_DIGEST_IE` | HTTP Digest authentication with an IE flavor. *The IE flavor is simply that libcurl will use a special "quirk" that IE is known to have used before version 7 and that some servers require the client to use.* | |
| 240 | | `CURLAUTH_NEGOTIATE` | HTTP Negotiate (SPNEGO) authentication. as defined in [RFC 4559](http://www.ietf.org/rfc/rfc4559.txt) | |
| 241 | | `CURLAUTH_NTLM` | HTTP NTLM authentication. A proprietary protocol invented and used by Microsoft. | |
| 242 | | `CURLAUTH_NTLM_WB` | NTLM delegating to winbind helper. Authentication is performed by a separate binary application. *see [libcurl docs](http://curl.haxx.se/libcurl/c/CURLOPT_HTTPAUTH.html) for more info* | |
| 243 | | `CURLAUTH_ANY` | This is a convenience macro that sets all bits and thus makes libcurl pick any it finds suitable. libcurl will automatically select the one it finds most secure. | |
| 244 | | `CURLAUTH_ANYSAFE` | This is a convenience macro that sets all bits except Basic and thus makes libcurl pick any it finds suitable. libcurl will automatically select the one it finds most secure. | |
| 245 | | `CURLAUTH_ONLY` | This is a meta symbol. OR this value together with a single specific auth value to force libcurl to probe for un-restricted auth and if not, only that single auth algorithm is acceptable. | |
| 246 | |
| 247 | ```php |
| 248 | // custom auth method |
| 249 | $configuration = Configuration::init() |
| 250 | ->proxyAuth('username', 'password', CURLAUTH_DIGEST); |
| 251 | ``` |
| 252 | ### Cookies |
| 253 | |
| 254 | Set a cookie string to specify the contents of a cookie header. Multiple cookies are separated with a semicolon followed by a space (e.g., "fruit=apple; colour=red") |
| 255 | |
| 256 | ```php |
| 257 | $configuration = Configuration::init() |
| 258 | ->cookie($cookie); |
| 259 | ``` |
| 260 | |
| 261 | Set a cookie file path for enabling cookie reading and storing cookies across multiple sequence of requests. |
| 262 | |
| 263 | ```php |
| 264 | $this->request->cookieFile($cookieFile) |
| 265 | ``` |
| 266 | |
| 267 | `$cookieFile` must be a correct path with write permission. |
| 268 | |
| 269 | ### Response Object |
| 270 | |
| 271 | Upon receiving a response Unirest returns the result in the form of an Object, this object should always have the same keys for each language regarding to the response details. |
| 272 | - `getStatusCode()` - HTTP Response Status Code (Example `200`) |
| 273 | - `getHeaders()` - HTTP Response Headers |
| 274 | - `getBody()` - Parsed response body where applicable, for example JSON responses are parsed to Objects / Associative Arrays. |
| 275 | - `getRawBody()` - Un-parsed response body |
| 276 | |
| 277 | ### Advanced Configuration |
| 278 | |
| 279 | You can set some advanced configuration to tune Unirest-PHP: |
| 280 | |
| 281 | #### Custom JSON Decode Flags |
| 282 | |
| 283 | Unirest uses PHP's [JSON Extension](http://php.net/manual/en/book.json.php) for automatically decoding JSON responses. |
| 284 | sometime you may want to return associative arrays, limit the depth of recursion, or use any of the [customization flags](http://php.net/manual/en/json.constants.php). |
| 285 | |
| 286 | To do so, simply set the desired options using the `jsonOpts` request method: |
| 287 | |
| 288 | ```php |
| 289 | $configuration = Configuration::init() |
| 290 | ->jsonOpts(true, 512, JSON_NUMERIC_CHECK & JSON_FORCE_OBJECT & JSON_UNESCAPED_SLASHES); |
| 291 | ``` |
| 292 | |
| 293 | #### Timeout |
| 294 | |
| 295 | You can set a custom timeout value (in **seconds**): |
| 296 | |
| 297 | ```php |
| 298 | $configuration = Configuration::init() |
| 299 | ->timeout(5); // 5s timeout |
| 300 | ``` |
| 301 | |
| 302 | #### Retries Related |
| 303 | |
| 304 | ```php |
| 305 | $configuration = Configuration::init() |
| 306 | ->enableRetries(true) // To enable retries feature |
| 307 | ->maxNumberOfRetries(10) // To set max number of retries |
| 308 | ->retryOnTimeout(false) // Should we retry on timeout |
| 309 | ->retryInterval(20) // Initial retry interval in seconds |
| 310 | ->maximumRetryWaitTime(30) // Maximum retry wait time |
| 311 | ->backoffFactor(1.1) // Backoff factor to be used to increase retry interval |
| 312 | ->httpStatusCodesToRetry([400,401]) // Http status codes to retry against |
| 313 | ->httpMethodsToRetry(['POST']) // Http methods to retry against |
| 314 | ``` |
| 315 | |
| 316 | #### Proxy |
| 317 | |
| 318 | Set the proxy to use for the upcoming request. |
| 319 | |
| 320 | you can also set the proxy type to be one of `CURLPROXY_HTTP`, `CURLPROXY_HTTP_1_0`, `CURLPROXY_SOCKS4`, `CURLPROXY_SOCKS5`, `CURLPROXY_SOCKS4A`, and `CURLPROXY_SOCKS5_HOSTNAME`. |
| 321 | |
| 322 | *check the [cURL docs](http://curl.haxx.se/libcurl/c/CURLOPT_PROXYTYPE.html) for more info*. |
| 323 | |
| 324 | ```php |
| 325 | // quick setup with default port: 1080 |
| 326 | $configuration = Configuration::init() |
| 327 | ->proxy('10.10.10.1'); |
| 328 | |
| 329 | // custom port and proxy type |
| 330 | $configuration = Configuration::init() |
| 331 | ->proxy('10.10.10.1', 8080, CURLPROXY_HTTP); |
| 332 | |
| 333 | // enable tunneling |
| 334 | $configuration = Configuration::init() |
| 335 | ->proxy('10.10.10.1', 8080, CURLPROXY_HTTP, true); |
| 336 | ``` |
| 337 | |
| 338 | ##### Proxy Authentication |
| 339 | |
| 340 | Passing a username, password *(optional)*, defaults to Basic Authentication: |
| 341 | |
| 342 | ```php |
| 343 | // basic auth |
| 344 | $configuration = Configuration::init() |
| 345 | ->proxyAuth('username', 'password'); |
| 346 | ``` |
| 347 | |
| 348 | The third parameter, which is a bitmask, will Unirest which HTTP authentication method(s) you want it to use for your proxy authentication. |
| 349 | |
| 350 | If more than one bit is set, Unirest *(at PHP's libcurl level)* will first query the site to see what authentication methods it supports and then pick the best one you allow it to use. *For some methods, this will induce an extra network round-trip.* |
| 351 | |
| 352 | See [Authentication](#authentication) for more details on methods supported. |
| 353 | |
| 354 | ```php |
| 355 | // basic auth |
| 356 | $configuration = Configuration::init() |
| 357 | ->proxyAuth('username', 'password', CURLAUTH_DIGEST); |
| 358 | ``` |
| 359 | |
| 360 | #### Default Request Headers |
| 361 | |
| 362 | You can set default headers that will be sent on every request: |
| 363 | |
| 364 | ```php |
| 365 | $configuration = Configuration::init() |
| 366 | ->defaultHeader('Header1', 'Value1') |
| 367 | ->defaultHeader('Header2', 'Value2'); |
| 368 | ``` |
| 369 | |
| 370 | You can set default headers in bulk by passing an array: |
| 371 | |
| 372 | ```php |
| 373 | $configuration = Configuration::init() |
| 374 | ->defaultHeaders([ |
| 375 | 'Header1' => 'Value1', |
| 376 | 'Header2' => 'Value2' |
| 377 | ]); |
| 378 | ``` |
| 379 | |
| 380 | You can clear the default headers anytime with: |
| 381 | |
| 382 | ```php |
| 383 | $configuration = Configuration::init() |
| 384 | ->clearDefaultHeaders(); |
| 385 | ``` |
| 386 | |
| 387 | #### Default cURL Options |
| 388 | |
| 389 | You can set default [cURL options](http://php.net/manual/en/function.curl-setopt.php) that will be sent on every request: |
| 390 | |
| 391 | ```php |
| 392 | $configuration = Configuration::init() |
| 393 | ->curlOpt(CURLOPT_COOKIE, 'foo=bar'); |
| 394 | ``` |
| 395 | |
| 396 | You can set options bulk by passing an array: |
| 397 | |
| 398 | ```php |
| 399 | $configuration = Configuration::init() |
| 400 | ->curlOpts(array( |
| 401 | CURLOPT_COOKIE => 'foo=bar' |
| 402 | )); |
| 403 | ``` |
| 404 | |
| 405 | You can clear the default options anytime with: |
| 406 | |
| 407 | ```php |
| 408 | $configuration = Configuration::init() |
| 409 | ->clearCurlOpts(); |
| 410 | ``` |
| 411 | |
| 412 | #### SSL validation |
| 413 | |
| 414 | You can explicitly enable or disable SSL certificate validation when consuming an SSL protected endpoint: |
| 415 | |
| 416 | ```php |
| 417 | $configuration = Configuration::init() |
| 418 | ->verifyPeer(false); // Disables SSL cert validation |
| 419 | ``` |
| 420 | |
| 421 | By default is `true`. |
| 422 | |
| 423 | #### Utility Methods |
| 424 | |
| 425 | ```php |
| 426 | // alias for `curl_getinfo` |
| 427 | $httpClient->getInfo(); |
| 428 | |
| 429 | ``` |
| 430 | |
| 431 | ---- |
| 432 | |
| 433 | [license-url]: https://github.com/apimatic/unirest-php/blob/master/LICENSE |
| 434 | [travis-url]: https://travis-ci.org/apimatic/unirest-php |
| 435 | [travis-image]: https://img.shields.io/travis/apimatic/unirest-php.svg?style=flat |
| 436 | [packagist-url]: https://packagist.org/packages/apimatic/unirest-php |
| 437 | [packagist-license]: https://img.shields.io/packagist/l/apimatic/unirest-php.svg?style=flat |
| 438 | [packagist-version]: https://img.shields.io/packagist/v/apimatic/unirest-php.svg?style=flat |
| 439 | [packagist-downloads]: https://img.shields.io/packagist/dm/apimatic/unirest-php.svg?style=flat |
| 440 |