PHP code example of zhanguangcheng / php-http-client
1. Go to this page and download the library: Download zhanguangcheng/php-http-client library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
use Zane\HttpClient\HttpClient;
use Zane\HttpClient\Options;
$client = HttpClient::create(
(new Options())
->setBaseUrl('https://...')
->setHeaders(['header-name' => 'header-value'])
->toArray()
);
use Zane\HttpClient\Options;
// it makes an HTTP GET request to https://httpbin.org/get?token=...&name=...
$response = $client->get('https://httpbin.org/get', [
// these values are automatically encoded before including them in the URL
'token' => '...',
'name' => '...',
]);
$response = $client->post('https://httpbin.org/post', [], [
Options::QUERY => [
'token' => '...',
'name' => '...',
]
]);
// defining data using a regular string
$response = $client->post('https://httpbin.org/post', 'raw data');
// defining data using an array of parameters
$response = $client->post('https://httpbin.org/post', ['parameter1' => 'value1', '...']);
// using a resource to get the data from it
$response = $client->post('https://httpbin.org/post', fopen('/path/to/file', 'r'));
// using a CURLFile object to upload a file
$response = $client->post('https://httpbin.org/post', [
'file' => new \CURLFile('/path/to/file'),
]);
$response = $client->request('GET', 'https://...');
// gets the HTTP status code of the response
$statusCode = $response->getStatusCode();
// gets the HTTP request error code. using function curl_errno()
$statusCode = $response->getErrorCode();
// gets the HTTP request error message. using function curl_error()
$statusCode = $response->getErrorMessage();
// gets the HTTP response headers as a string
$headers = $response->getHeaderLine('content-type');
// gets the HTTP response headers as an array of strings
$headers = $response->getHeader('content-type');
// gets the HTTP headers as string[][] with the header names lower-cased
$headers = $response->getHeaders();
// gets the response body as a string
$content = $response->getContent();
// casts the response JSON content to a PHP array
$content = $response->toArray();
// returns info coming from the transport layer, such as "request_header",
// "retry_count", "total_time", "redirect_url", etc.
$httpInfo = $response->getInfo();
// you can get individual info too
$startTime = $response->getInfo('request_header');
// gets the request options
$options = $response->getOptions();
$options->getQuery();