PHPackages                             phputility/async - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. phputility/async

ActiveLibrary[HTTP &amp; Networking](/categories/http)

phputility/async
================

A lightweight PHP library for asynchronous HTTP requests using curl\_multi\_\* functions

001PHP

Since Oct 17Pushed 7mo agoCompare

[ Source](https://github.com/ransomfeed/phputils-async)[ Packagist](https://packagist.org/packages/phputility/async)[ RSS](/packages/phputility-async/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

phputils-async
==============

[](#phputils-async)

[![PHP Version](https://camo.githubusercontent.com/204b1791e3a57f86a93de1422b2a6e584f5045431629c5b9abd4e28dbc8b5357/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344372e342d626c75652e737667)](https://php.net)[![License](https://camo.githubusercontent.com/8bb50fd2278f18fc326bf71f6e88ca8f884f72f179d3e555e20ed30157190d0d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e2e737667)](LICENSE)[![Build Status](https://camo.githubusercontent.com/c27a457659b89ee4f1f80f7995c559dd37f2051bde7167ad25791e5c5c92cc8e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6275696c642d70617373696e672d627269676874677265656e2e737667)](https://github.com/ransomfeed/phputils-async)

A lightweight PHP library for asynchronous HTTP requests using native `curl_multi_*` functions. No external dependencies required!

Features
--------

[](#features)

- 🚀 **Asynchronous HTTP requests** using `curl_multi_*` functions
- 🔄 **Automatic fallback** to synchronous requests if async is not available
- ⚡ **Concurrency control** - limit the number of parallel requests
- 🎯 **Simple API** - clean and intuitive interface
- 📦 **Zero dependencies** - uses only PHP built-in functions
- 🔧 **Flexible configuration** - custom headers, timeouts, and options
- 📊 **Response objects** - structured response handling
- 🧪 **Well tested** - comprehensive test suite included

Requirements
------------

[](#requirements)

- PHP 7.4 or higher
- cURL extension enabled

Installation
------------

[](#installation)

```
composer require phputility/async
```

Or add it to your `composer.json`:

```
{
    "require": {
        "phputility/async": "^1.0"
    }
}
```

Quick Start
-----------

[](#quick-start)

### Basic GET Requests

[](#basic-get-requests)

```
use Phputils\Async\HttpClient;

$client = new HttpClient([
    'timeout' => 5,
    'headers' => ['User-Agent: MyApp/1.0']
]);

$responses = $client->get([
    'https://api.github.com',
    'https://httpbin.org/get',
    'https://api.ransomfeed.it'
]);

foreach ($responses as $url => $response) {
    echo "[$url] Status: " . $response['status'] . "\n";
    echo "Body length: " . strlen($response['body']) . "\n\n";
}
```

### POST Requests

[](#post-requests)

```
$requests = [
    ['url' => 'https://httpbin.org/post', 'body' => 'Hello World'],
    ['url' => 'https://httpbin.org/post', 'body' => '{"key": "value"}']
];

$responses = $client->post($requests);

foreach ($responses as $url => $response) {
    if ($response['status'] === 200) {
        echo "Success: $url\n";
    }
}
```

### Using Request Objects

[](#using-request-objects)

```
use Phputils\Async\Request;

$requests = [
    Request::get('https://api.example.com/data'),
    Request::post('https://api.example.com/create', '{"name": "test"}')
        ->addHeader('Content-Type', 'application/json'),
    Request::put('https://api.example.com/update/1', '{"status": "active"}')
];

$responses = $client->request('GET', $requests);
```

Advanced Usage
--------------

[](#advanced-usage)

### Concurrency Control

[](#concurrency-control)

```
$client = new HttpClient([
    'concurrency' => 5,  // Maximum 5 parallel requests
    'timeout' => 10
]);

$urls = array_fill(0, 20, 'https://httpbin.org/delay/1');
$responses = $client->get($urls);

// This will process 5 requests at a time, taking about 4 seconds total
```

### Custom Headers and Options

[](#custom-headers-and-options)

```
$client = new HttpClient([
    'headers' => [
        'Authorization: Bearer token123',
        'X-API-Version: v2'
    ],
    'timeout' => 15
]);

// Override headers for specific requests
$responses = $client->get(['https://api.example.com'], [
    'headers' => ['X-Custom: value']
]);
```

### Callback Function

[](#callback-function)

```
$processedCount = 0;

$callback = function ($url, $response) use (&$processedCount) {
    $processedCount++;
    echo "Processed $processedCount: $url - Status: {$response['status']}\n";

    if ($response['status'] === 200) {
        // Process successful response
        $data = json_decode($response['body'], true);
        // ... handle data
    }
};

$responses = $client->get($urls, ['callback' => $callback]);
```

### Error Handling

[](#error-handling)

```
$urls = [
    'https://httpbin.org/status/200',
    'https://httpbin.org/status/404',
    'https://invalid-domain.com'
];

$responses = $client->get($urls);

foreach ($responses as $url => $response) {
    if (!empty($response['error'])) {
        echo "Error for $url: {$response['error']}\n";
    } elseif ($response['status'] >= 400) {
        echo "HTTP Error for $url: {$response['status']}\n";
    } else {
        echo "Success for $url: {$response['status']}\n";
    }
}
```

API Reference
-------------

[](#api-reference)

### HttpClient

[](#httpclient)

#### Constructor

[](#constructor)

```
new HttpClient(array $options = [])
```

**Options:**

- `timeout` (int): Request timeout in seconds (default: 30)
- `headers` (array): Default headers for all requests
- `concurrency` (int): Maximum parallel requests (default: 10)
- `callback` (callable): Callback function for each completed request
- `user_agent` (string): User agent string (default: 'phputils-async/1.0')

#### Methods

[](#methods)

##### `get(array $urls, array $options = []): array`

[](#getarray-urls-array-options---array)

Execute GET requests asynchronously.

##### `post(array $requests, array $options = []): array`

[](#postarray-requests-array-options---array)

Execute POST requests asynchronously.

##### `request(string $method, array $requests, array $options = []): array`

[](#requeststring-method-array-requests-array-options---array)

Execute requests with specified HTTP method.

##### `isAsyncAvailable(): bool`

[](#isasyncavailable-bool)

Check if curl\_multi\_\* functions are available.

### Request

[](#request)

#### Static Methods

[](#static-methods)

```
Request::get(string $url, array $headers = [], array $options = []): Request
Request::post(string $url, string $body = null, array $headers = [], array $options = []): Request
Request::put(string $url, string $body = null, array $headers = [], array $options = []): Request
Request::delete(string $url, string $body = null, array $headers = [], array $options = []): Request
```

#### Instance Methods

[](#instance-methods)

```
$request->addHeader(string $name, string $value): Request
$request->setBody(string $body): Request
$request->setOption(string $key, mixed $value): Request
$request->toArray(): array
```

### Response

[](#response)

#### Properties

[](#properties)

- `$status` (int|null): HTTP status code
- `$headers` (array): Response headers
- `$body` (string): Response body
- `$error` (string|null): Error message
- `$info` (array): Additional cURL info

#### Methods

[](#methods-1)

```
$response->isSuccess(): bool  // Check if status is 200-299
$response->toArray(): array   // Convert to array format
```

Performance
-----------

[](#performance)

### Benchmark Example

[](#benchmark-example)

```
$urls = array_fill(0, 10, 'https://httpbin.org/delay/1');

// Async execution
$start = microtime(true);
$asyncResponses = $client->get($urls);
$asyncTime = microtime(true) - $start;

// Sequential execution
$start = microtime(true);
$sequentialClient = new HttpClient(['concurrency' => 1]);
$sequentialResponses = $sequentialClient->get($urls);
$sequentialTime = microtime(true) - $start;

echo "Async time: " . round($asyncTime, 2) . "s\n";
echo "Sequential time: " . round($sequentialTime, 2) . "s\n";
echo "Speed improvement: " . round($sequentialTime / $asyncTime, 2) . "x\n";
```

**Typical results:**

- Async: ~1.2 seconds
- Sequential: ~10.1 seconds
- **Speed improvement: ~8.4x faster**

Testing
-------

[](#testing)

Run the test suite:

```
composer test
```

Run with coverage:

```
composer test-coverage
```

Run code quality checks:

```
composer quality
```

Contributing
------------

[](#contributing)

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

License
-------

[](#license)

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

Changelog
---------

[](#changelog)

### 1.0.0

[](#100)

- Initial release
- Async HTTP requests with curl\_multi\_\*
- Concurrency control
- Request/Response objects
- Comprehensive test suite
- Zero external dependencies

Support
-------

[](#support)

If you encounter any issues or have questions, please:

1. Check the [Issues](https://github.com/ransomfeed/phputils-async/issues) page
2. Create a new issue with detailed information
3. For questions, use the [Discussions](https://github.com/ransomfeed/phputils-async/discussions) page

---

Made with ❤️ by the Nuke{} (Ransomfeed team)

###  Health Score

17

—

LowBetter than 6% of packages

Maintenance45

Moderate activity, may be stable

Popularity1

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity13

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/1aeaac0caf5b7a95963fff8070eda28d90a09b6a04abe25c6140adff9294f942?d=identicon)[nuke](/maintainers/nuke)

---

Top Contributors

[![ransomfeed](https://avatars.githubusercontent.com/u/224285569?v=4)](https://github.com/ransomfeed "ransomfeed (3 commits)")

### Embed Badge

![Health badge](/badges/phputility-async/health.svg)

```
[![Health](https://phpackages.com/badges/phputility-async/health.svg)](https://phpackages.com/packages/phputility-async)
```

###  Alternatives

[friendsofsymfony/rest-bundle

This Bundle provides various tools to rapidly develop RESTful API's with Symfony

2.8k73.3M319](/packages/friendsofsymfony-rest-bundle)[php-http/discovery

Finds and installs PSR-7, PSR-17, PSR-18 and HTTPlug implementations

1.3k309.5M1.2k](/packages/php-http-discovery)[pusher/pusher-php-server

Library for interacting with the Pusher REST API

1.5k94.8M293](/packages/pusher-pusher-php-server)[react/http

Event-driven, streaming HTTP client and server implementation for ReactPHP

78026.4M414](/packages/react-http)[php-http/curl-client

PSR-18 and HTTPlug Async client with cURL

48347.0M384](/packages/php-http-curl-client)[smi2/phpclickhouse

PHP ClickHouse Client

84310.1M71](/packages/smi2-phpclickhouse)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
