xicrow/php-curl

PHP wrapper and tools for cURL

1.0.0 2022-09-17 11:11 UTC

This package is not auto-updated.

Last update: 2024-04-28 17:24:52 UTC


README

PHP Wrapper and tools for cURL

Note: Early version still subject to major changes

Installation

The recommended way to install is through Composer.

composer require xicrow/php-curl

Or add directly to composer.json

{
    "require": {
        "xicrow/php-curl": "~1.0"
    }
}

Examples

Request

Create new Request

$request = new Request();

Set cUrl options on Request construct

$request = new Request([
    CURLOPT_URL       => 'example.com',
    CURLOPT_USERAGENT => 'Mozilla/4.0',
    CURLOPT_TIMEOUT   => 5,
]);

Set cUrl options through CurlOptions instance on Request

$request->curlOptions()->set(CURLOPT_URL, 'example.com')->set(CURLOPT_USERAGENT, 'Mozilla/4.0');
$request->curlOptions()->set([
    CURLOPT_TIMEOUT        => 5,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_MAXREDIRS      => 3,
]);

Response

Get Response from executing Request

$response = $request->execute();

Get body from Response

$response->body();

Get all headers from Headers instance on Response

$response->headers()->get();

Get specific headers from Headers instance on Response

$response->headers()->getHttpStatusCode();
$response->headers()->get('Http-Status-Code');
$response->headers()->get([
    'Http-Status-Code',
    'Http-Status-Message',
]);

Batch

Create new Batch with options

$batch = new Batch([
    'max_concurrent_requests' => 5,
]);

Add Request one at a time

$batch->addRequest(new Request());

Or add multiple Requests at once

$batch->addRequests([
    new Request(),
    new Request(),
    new Request(),
]);

Set CurlOptions on Batch which will merge with CurlOptions on Request

$batch->curlOptions()->set([
    CURLOPT_CUSTOMREQUEST  => 'GET',
    CURLOPT_PORT           => 80,
]);

Execute Batch and loop Requests and Responses
Note: there are several ways to match Request to Response this is mainly for illustrative purpose

$batch->execute();
foreach ($batch->getRequests() as $requestIndex => $request) {
    foreach ($batch->getResponses() as $responseIndex => $response) {
        // Skip if request and response index does not match
        if ($requestIndex != $responseIndex) {
            continue;
        }

        // ...
    }
}

TODO

  • Unit tests
  • More utility methods for CurlOptions
  • More utility methods for Headers
  • Maybe refractor CurlOptions and Headers and how to get/set them

License

Copyright © 2022 Jan Ebsen. Licensed under the MIT license.