PHP code example of callismart / http

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

    

callismart / http example snippets


use Callismart\Http\HttpClient;

$client   = new HttpClient();
$response = $client->get( 'https://api.example.com/v1/resource' );

if ( $response->ok() ) {
    $data = $response->json();
    print_r( $data );
}

$response = $client->post_json( 'https://api.example.com/v1/users', [
    'name'  => 'Callistus',
    'role'  => 'Developer',
    'email' => '[email protected]',
] );

if ( $response->is_success() ) {
    $user = $response->json();
    echo "Created user ID: {$user['id']}";
}

$response = $client->download(
    'https://example.com/releases/plugin-2.1.0.zip',
    '/var/www/downloads/plugin-2.1.0.zip'
);

if ( $response->is_success() ) {
    echo "Saved {$response->file_size} bytes to {$response->sink_path}";
}

use Callismart\Http\HttpRequest;
use Callismart\Http\AwsSignatureV4;

$request = HttpRequest::post( 'https://email.us-east-1.amazonaws.com/', $body )
    ->with_header( 'Content-Type', 'application/x-www-form-urlencoded' );

$signer   = new AwsSignatureV4( $access_key, $secret_key, 'us-east-1', 'ses' );
$signed   = $signer->sign( $request );
$response = $client->send( $signed );

$client = new HttpClient();
// Automatically uses the first available adapter

use Callismart\Http\Adapters\CurlAdapter;
use Callismart\Http\Adapters\FopenAdapter;
use Callismart\Http\Adapters\SocketAdapter;

// Force cURL
$client = new HttpClient( new CurlAdapter() );

// Force fopen
$client = new HttpClient( new FopenAdapter() );

// Force socket (always available)
$client = new HttpClient( new SocketAdapter() );

$adapter = $client->get_adapter();
echo "Using adapter: " . $adapter->get_id(); // "curl", "fopen", or "socket"

$client->with_default_header( 'Authorization', "Bearer {$token}" )
       ->with_default_header( 'User-Agent', 'MyApp/1.0' );

// These headers are merged into every request sent via this client
$response = $client->get( 'https://api.example.com/user' );
// Automatically 

use Callismart\Http\HttpRequest;

// GET
$request = HttpRequest::get( 'https://api.example.com/posts' );

// POST
$request = HttpRequest::post( 'https://api.example.com/posts', $body );

// PUT
$request = HttpRequest::put( 'https://api.example.com/posts/123', $body );

// PATCH
$request = HttpRequest::patch( 'https://api.example.com/posts/123', $body );

// DELETE
$request = HttpRequest::delete( 'https://api.example.com/posts/123' );

$request = HttpRequest::get( $url )
    ->with_header( 'Authorization', "Bearer {$token}" )
    ->with_header( 'X-Custom-Header', 'value' );

$request = HttpRequest::post( $url )
    ->with_json( [
        'name'  => 'Alice',
        'email' => '[email protected]',
    ] );

// Equivalent to:
// $request = HttpRequest::post( $url, json_encode( [...] ) )
//     ->with_header( 'Content-Type', 'application/json' )
//     ->with_header( 'Accept', 'application/json' );

$request = HttpRequest::get( $url )
    ->with_cookie( 'session_id', 'abc123' )
    ->with_cookie( 'user_pref', 'dark_mode' );

// Cookies are automatically formatted into the Cookie header

$request = HttpRequest::get( 'https://example.com/large-file.zip' )
    ->with_sink( '/tmp/large-file.zip' );

$response = $client->send( $request );

if ( $response->is_success() ) {
    echo "File saved to: {$response->sink_path}";
    echo "File size: {$response->file_size} bytes";
}

$request = HttpRequest::get( 'https://self-signed.example.com' )
    ->without_ssl_verification();

$request = HttpRequest::get( $url )->with_options( [
    'timeout'       => 60,           // seconds
    'verify_ssl'    => false,        // boolean
    'max_redirects' => 10,           // integer
    'cookies'       => [             // array of name => value
        'session_id' => 'xyz789',
    ],
] );

$response = $client->send( $request );

// GET
$response = $client->get( 'https://api.example.com/users' );

// POST with body
$response = $client->post( 'https://api.example.com/users', $json_body );

// POST with JSON (automatic encoding + headers)
$response = $client->post_json( 'https://api.example.com/users', [
    'name' => 'Bob',
] );

// PUT
$response = $client->put( 'https://api.example.com/users/123', $body );

// PATCH
$response = $client->patch( 'https://api.example.com/users/123', $body );

// DELETE
$response = $client->delete( 'https://api.example.com/users/123' );

// Download (with automatic streaming)
$response = $client->download( $url, '/path/to/file' );

$response = $client->get( $url );

// Shorthand for is_success()
if ( $response->ok() ) {
    // 2xx status
}

// Detailed checks
if ( $response->is_success() ) {
    // 200-299
}

if ( $response->is_client_error() ) {
    // 400-499
}

if ( $response->is_server_error() ) {
    // 500-599
}

if ( $response->is_error() ) {
    // 400-599
}

if ( $response->is_redirect() ) {
    // 300-399
}

// JSON decoding
$data = $response->json(); // returns decoded array (or null if invalid)

// Check if body is valid JSON
if ( $response->is_json() ) {
    $data = $response->json();
}

// Raw body as string
$raw = $response->body;

// Get a single header (case-insensitive)
$content_type = $response->get_header( 'content-type' );

// Check if header exists
if ( $response->has_header( 'content-length' ) ) {
    // ...
}

// Shorthand for Content-Type
$type = $response->content_type(); // e.g. "application/json; charset=utf-8"

// All headers as associative array
$headers = $response->headers; // keys are lowercase

// Get a single cookie
$session_id = $response->get_cookie( 'session_id' );

// Check if cookie exists
if ( $response->has_cookie( 'session_id' ) ) {
    // ...
}

// All cookies as associative array
$cookies = $response->cookies;

// Check if any redirects were followed
if ( $response->was_redirected() ) {
    echo "Original URL: {$response->original_url()}";
    echo "Final URL: {$response->final_url()}";
}

// Complete redirect history (ordered list of URLs)
foreach ( $response->redirect_history as $url ) {
    echo "Followed: {$url}\n";
}

$response = $client->download( $url, '/tmp/file.zip' );

// Check if response was streamed to file
if ( $response->is_download() ) {
    echo "File: {$response->sink_path}";
    echo "Size: {$response->file_size} bytes";
    echo "Body is empty: " . ( $response->body === '' ? 'yes' : 'no' );
}

$response = $client->get( $url ); // buffered in memory

if ( $response->is_success() ) {
    $response->save_to( '/tmp/file.zip' ); // write to disk
}

$response = $client->get( $url );

echo "Request took {$response->latency} seconds";

$response = $client->get( 'https://api.example.com/posts/42' );

if ( $response->is_success() ) {
    $post = $response->json();
    echo "Title: {$post['title']}";
}

$response = $client->post_json( 'https://api.example.com/posts', [
    'title'   => 'Hello World',
    'content' => 'This is my first post.',
    'author'  => 'Alice',
] );

if ( $response->is_success() ) {
    $created = $response->json();
    echo "Post created with ID: {$created['id']}";
}

$request = HttpRequest::post( $url, $body )
    ->with_header( 'Content-Type', 'application/x-www-form-urlencoded' )
    ->with_header( 'X-API-Key', 'secret' );

$response = $client->send( $request );

$response = $client->put_json( 'https://api.example.com/posts/42', [
    'title'   => 'Updated Title',
    'content' => 'Updated content.',
    'author'  => 'Alice',
] );

$response = $client->patch_json( 'https://api.example.com/posts/42', [
    'title' => 'New Title Only',
] );

$response = $client->delete( 'https://api.example.com/posts/42' );

if ( $response->is_success() ) {
    echo "Post deleted";
}

$request = HttpRequest::post( $url )
    ->with_json( [ 'key' => 'value' ] );

// Headers set automatically:
// Content-Type: application/json
// Accept: application/json

$response = $client->post_json( $url, $data );

// Returns decoded array (or null if invalid/empty)
$result = $response->json();

// Check validity first
if ( $response->is_json() ) {
    $result = $response->json();
} else {
    echo "Response is not valid JSON";
}

$response = $client->download(
    'https://example.com/releases/large-file-100mb.zip',
    '/var/downloads/large-file.zip'
);

if ( $response->is_success() ) {
    echo "Downloaded {$response->file_size} bytes";
} else {
    echo "Download failed with status {$response->status_code}";
}

$response = $client->get( 'https://example.com/image.png' );

if ( $response->is_success() ) {
    $response->save_to( '/var/downloads/image.png' );
}

$request = HttpRequest::get( $url )->with_sink( '/tmp/download.zip' );
$response = $client->send( $request );

if ( $response->is_download() ) {
    echo "Saved to {$response->sink_path}";
}

use Callismart\Http\AwsSignatureV4;

$signer = new AwsSignatureV4(
    access_key: 'AKIAIOSFODNN7EXAMPLE',
    secret_key: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
    region:     'us-east-1',
    service:    'ses', // or 's3', 'lambda', etc.
);

$request = HttpRequest::post( 'https://email.us-east-1.amazonaws.com/', $body )
    ->with_header( 'Content-Type', 'application/x-www-form-urlencoded' );

$signed = $signer->sign( $request );

// Headers automatically added:
// - X-Amz-Date: 20250512T123456Z
// - X-Amz-Content-Sha256: (SHA256 hash of body)
// - Authorization: AWS4-HMAC-SHA256 Credential=..., SignedHeaders=..., Signature=...

$response = $client->send( $signed );

$body = http_build_query( [
    'Action'                   => 'SendEmail',
    'Source'                   => '[email protected]',
    'Destination.ToAddresses.1' => '[email protected]',
    'Message.Subject.Data'      => 'Hello!',
    'Message.Body.Text.Data'    => 'This is a test email.',
] );

$request = HttpRequest::post( 'https://email.us-east-1.amazonaws.com/', $body )
    ->with_header( 'Content-Type', 'application/x-www-form-urlencoded' );

$signer   = new AwsSignatureV4( $key, $secret, 'us-east-1', 'ses' );
$signed   = $signer->sign( $request );
$response = $client->send( $signed );

if ( $response->is_success() ) {
    $xml = $response->body;
    // Parse XML response...
}

$request = HttpRequest::get( 'https://my-bucket.s3.amazonaws.com/config.json' );

$signer   = new AwsSignatureV4( $key, $secret, 'us-east-1', 's3' );
$signed   = $signer->sign( $request );
$response = $client->send( $signed );

if ( $response->is_success() ) {
    $config = $response->json();
}

use Callismart\Http\Adapters\CurlAdapter;

$adapter = new CurlAdapter();
if ( $adapter->is_available() ) {
    echo "cURL is available";
}

use Callismart\Http\Adapters\FopenAdapter;

$adapter = new FopenAdapter();
if ( $adapter->is_available() ) {
    echo "fopen streaming is available";
}

use Callismart\Http\Adapters\SocketAdapter;

$adapter = new SocketAdapter();
if ( $adapter->is_available() ) {
    echo "Socket fallback is available";
}

$client = new HttpClient();
// Automatically selects cURL → fopen → socket

// If none are available, throws HttpRequestException:
// "HttpClient: no HTTP adapter is available in this environment. 
//  Enable cURL, allow_url_fopen, or fsockopen."

$client = new HttpClient( new SocketAdapter() );
// Uses socket even if cURL is available

use Callismart\Http\Exceptions\HttpRequestException;
use Callismart\Http\Exceptions\HttpTimeoutException;

try {
    $response = $client->get( $url );
} catch ( HttpTimeoutException $e ) {
    // Request exceeded timeout
    echo "Timeout: {$e->getMessage()}";
} catch ( HttpRequestException $e ) {
    // Connection failed, DNS error, socket error, etc.
    echo "Error: {$e->getMessage()}";
}

$request = HttpRequest::get( $url )->with_options( [
    'timeout'       => 30,       // seconds (default: 30)
    'verify_ssl'    => true,     // boolean (default: true)
    'max_redirects' => 5,        // integer (default: 5)
    'cookies'       => [],       // array of name => value
    'sink'          => null,     // absolute path for streaming
] );

$client = new HttpClient();

// Set default headers
$client->with_default_header( 'Authorization', "Bearer {$token}" );
$client->with_default_header( 'User-Agent', 'MyApp/1.0' );

// Check current adapter
$adapter_id = $client->get_adapter()->get_id(); // "curl", "fopen", or "socket"

   $request = HttpRequest::get( $url )->with_options( [ 'timeout' => 60 ] );
   

   if ( count( $response->redirect_history ) > 10 ) {
       // Possible redirect loop
   }