PHP code example of elfsundae / httpclient

1. Go to this page and download the library: Download elfsundae/httpclient 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/ */

    

elfsundae / httpclient example snippets


use ElfSundae\HttpClient;

$html = (new HttpClient)->fetchContent('http://httpbin.org');

$data = (new HttpClient)->fetchJson('https://httpbin.org/ip');

$client = HttpClient::create('https://httpbin.org')
    ->catchExceptions(true)
    ->httpErrors(false)
    ->auth(['user', 'passwd']);

$query = $client->query(['foo' => 'bar'])->getJson('/get');

$form = $client->formParams(['foo' => 'bar'])->postJson('/post');

$json = $client->json(['foo' => 'bar'])->putJson('/put');

$download = $client->saveTo('image.png')->get('/image/png');

$file = fopen('image.png', 'r');
$uploadBody = $client->body($file)->postJson('/post');

$multipart = [
    'foo' => 'bar',
    'file' => $file,
    'image' => [
        'contents' => fopen('image.png', 'r'),
        'filename' => 'filename.png',
    ],
];
$formData = $client->multipart($multipart)->postJson('/post');

$promise = $client->json($data)->getAsync('/get');

$promise = $client->formParams($data)->postAsync('/post');

$client
    ->option('cert', $cert)
    ->option([
        'debug' => true,
        'headers.Content-Type' => 'application/json',
    ]);

$client
    ->allowRedirects(false)
    ->timeout(20)
    ->cookies($cookieJar)
    ->headers([
        'X-Foo' => 'foo',
    ]);

$client
    ->header('X-Foo', 'foo');
    ->header('X-Bar', 'bar');
    ->acceptJson()
    ->contentType('text/plain')
    ->userAgent('HttpClient/2.0')

HttpClient::setDefaultOptions([
    'catch_exceptions' => true,
    'http_errors' => false,
    'connect_timeout' => 5,
    'timeout' => 20,
    'headers.User-Agent' => 'HttpClient/2.0',
]);

$response = $client->catchExceptions(true)->get('/api/path');

try {
    $response = $client->catchExceptions(false)->get('/api/path');
} catch (Exception $e) {
    // ...
}