PHPackages                             arturdoruch/http - 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. arturdoruch/http

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

arturdoruch/http
================

HTTP client for sending HTTP requests.

3.7.2(4y ago)1557MITPHPPHP &gt;=5.4

Since Feb 8Pushed 4y ago1 watchersCompare

[ Source](https://github.com/arturdoruch/Http)[ Packagist](https://packagist.org/packages/arturdoruch/http)[ RSS](/packages/arturdoruch-http/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (1)Versions (39)Used By (0)

Http
====

[](#http)

HTTP client for sending HTTP requests.

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

[](#installation)

```
composer require "arturdoruch/http"

```

Usage
-----

[](#usage)

### Basic usage

[](#basic-usage)

```
use ArturDoruch\Http\Client;

$client = new Client();
// Send GET request.
$response = $client->get('http://httpbin.org/get');

// Get response status code.
$statusCode = $response->getStatusCode();

// Get response body.
$body = $response->getBody();

// Display response raw headers and body.
echo $response;

// Display response headers.
foreach ($response->getHeaders() as $name => $value) {
    echo sprintf("%s: %s\n", $name, $value);
}
```

### Creating a client

[](#creating-a-client)

```
use ArturDoruch\Http\Cookie\CookieFile;
use ArturDoruch\Http\Client;

// Set the cURL options, which will be used for send every HTTP request.
$curlOptions = [
    'followlocation' => false,
    'timeout' => 120
];

// Enabled or disabled throwing RequestException, when request is complete and response status code is 4xx, 5xx or 0.
$throwExceptions = true;

// Set file where all HTTP session cookies should be stored.
$cookieFile = new CookieFile('path/to/cookies.txt');

$client = new Client($curlOptions, $throwExceptions, $cookieFile);
```

### Sending requests

[](#sending-requests)

Request can be send with dedicated methods:

```
$response = $client->get('http://httpbin.org/get');
$response = $client->post('http://httpbin.org/post');
$response = $client->patch('http://httpbin.org/patch');
$response = $client->put('http://httpbin.org/put');
$response = $client->delete('http://httpbin.org/delete');
```

or by `request()` method, with prepared the `ArturDoruch\Http\Request` object.

```
use ArturDoruch\Http\Request;

$request = new Request('DELETE', 'http://httpbin.org/delete');
$response = $client->request($request);
```

### Sending multi (parallel) requests

[](#sending-multi-parallel-requests)

```
$requests = [
    // The list of ArturDoruch\Http\Request objects or URLs to send.
];
$responses = $client->multiRequest($requests);

foreach ($responses as $response) {
    var_dump($response->getBody());
}
```

### Sending form data (parameters)

[](#sending-form-data-parameters)

```
$formData = [
    'name' => 'value',
    'choices' => [1, 2, 3]
];

$response = $client->post('http://httpbin.org/post', $formData);

$request = new Request('POST', 'http://httpbin.org/post', $formData);
$response = $client->request($request);
```

Form data can be send only with the request methods: `POST`, `PUT`, `PATCH` and `DELETE`. For other methods form data will be used as the URL query parameters.

### Request options

[](#request-options)

Request options can be set with dedicated methods on the `ArturDoruch\Http\Request` object, or as the third argument in the `Client::get()`, `Client::post()`, etc. methods, or as the fourth argument in the `Client::createRequest()` method.

- `cookie` string

    Sets the cookie to send. The cookie format must conform to the [specification](http://curl.haxx.se/rfc/cookie_spec.html).

    ```
    $client->get('/get', [], [
        'cookie' => 'NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN_NAME; secure'
    ]);
    ```
- `headers` array

    ```
    $client->get('/get', [], [
        'headers' => [
            'User-Agent' => 'testing/1.0',
            'Accept' => 'application/json',
            'X-Foo' => ['Bar', 'Baz']
        ]
    ]);
    ```
- `body` string|resource

    Sets the body plain text. If the `Content-Type` header is not specified then will be set to `text/plain`.

    ```
    // Send body as plain text taken from a resource.
    $resource = fopen('http://httpbin.org', 'r');
    $client->post('/post', [], ['body' => $resource]);

    // Send plain text.
    $client->post('/post', [], ['body' => 'Raw data']);
    ```
- `json` array

    Sets the body to JSON data. If the `Content-Type` header is not specified then will be set to `application/json`.

    ```
    $client->post('/post', [], [
        'json' => [
            'foo' => 'bar',
            'key' => 'value'
        ]
    ]);
    ```
- `multipart` array

    Sets the body to a multipart form data. For sending file create the `ArturDoruch\Http\Message\FormFile` object and pass as the form field value. If the `Content-Type` header is not specified then will be set to `multipart/form-data; boundary=`.

    ```
    use ArturDoruch\Http\Message\FormFile;

    $client->post('/post', [], [
        'multipart' => [
            'name' => 'value',
            'categories' => [
                'animals' => ['dog', 'cat'],
            ],
            'file' => new FormFile('/path/file.txt.', 'optional-custom-filename.txt')
        ]
    ]);
    ```

### HTTP request events

[](#http-request-events)

While HTTP request is sending, are called two events:

- `request.before` - Called before sending the request.
- `request.complete` - Called when the request is done.

To add listeners for those events call the `Client::addListener()` method. Registered listeners receives argument depend on the event to listen for. One of the:

- `ArturDoruch\Http\Event\BeforeEvent` - for the `request.before` event
- `ArturDoruch\Http\Event\CompleteEvent` - for the `request.complete` event

```
use App\EventListener\HttpRequestListener;
use ArturDoruch\Http\Event\BeforeEvent;
use ArturDoruch\Http\Event\CompleteEvent;
use ArturDoruch\Http\Event\RequestEvents;

// Add listener to request.before event as anonymous function.
$client->addListener(RequestEvents::BEFORE, function (BeforeEvent $event) {
    $request = $event->getRequest();
});

// Add listener to request.before event as method class.
$client->addListener(RequestEvents::BEFORE, [new HttpRequestListener(), 'onBefore']);

// Add listener to request.complete event as method class.
$client->addListener(RequestEvents::COMPLETE, [new HttpRequestListener(), 'onComplete']);
```

Example of the `HttpRequestListener` class.

```
namespace App\EventListener;

use ArturDoruch\Http\Event\BeforeEvent;
use ArturDoruch\Http\Event\CompleteEvent;

class HttpRequestListener
{
    /**
     * @param BeforeEvent $event
     */
    public function onBefore(BeforeEvent $event)
    {
        $request = $event->getRequest();
        // Do some actions before HTTP request is sending.
    }

    /**
     * @param CompleteEvent $event
     */
    public function onComplete(CompleteEvent $event)
    {
        $response = $event->getResponse();
        // Do some actions when HTTP request is complete.
    }
}
```

### Convert Response object to array or json

[](#convert-response-object-to-array-or-json)

In order to convert Response object to array call Response::toArray() method.

```
$responseArray = $response->toArray();
```

In order to convert Response object to json call Response::toJson() method.

```
$responseJson = $response->toJson();
// Use JSON_PRETTY_PRINT option to format output json
$responseJson = $response->toJson(true);
```

To determine which Response object properties should be available in converted output value use Response::expose() method. This method takes an argument "properties" with list of properties names to expose. Available names are:

- protocol
- statusCode
- reasonPhrase
- headers
- headerLines
- body
- contentType
- requestUrl
- effectiveUrl
- errorMsg
- errorNumber
- curlInfo

As default are exposed properties: statusCode, headers, body.

```
// Expose only the "statusCode" and "body" properties.
$response->expose([
    'statusCode',
    'body',
]);
// The array will contain only "statusCode" and "body" keys.
$responseArray = $response->toArray();
```

To expose all Response properties use exposeAll() method.

```
// Expose all properties.
$response->exposeAll();
// The array will contain all of available properties.
$responseArray = $response->toArray();
```

Tips
----

[](#tips)

- Get actually sent request headers. ```
    $client = new Client([CURLINFO_HEADER_OUT => true]);

    $response = $client->get('http://httpbin.org/get');
    $curlInfo = $response->getCurlInfo()

    $requestHeaders = $curlInfo['request_header'];
    ```

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity15

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity70

Established project with proven stability

 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.

###  Release Activity

Cadence

Every ~65 days

Recently: every ~78 days

Total

38

Last Release

1679d ago

Major Versions

1.1.0 → 2.0.02015-03-11

2.0.2 → 3.0.02015-04-29

PHP version history (2 changes)1.1.0PHP &gt;=5.3.3

3.4.0PHP &gt;=5.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/5af341236bd5f7de04934e7b63ab71d774df81f5409e7fafd19ede18c0cd6c2a?d=identicon)[arturdoruch](/maintainers/arturdoruch)

---

Top Contributors

[![arturdoruch](https://avatars.githubusercontent.com/u/6686928?v=4)](https://github.com/arturdoruch "arturdoruch (125 commits)")

---

Tags

curlhttp clienthttp requestmulti requests

### Embed Badge

![Health badge](/badges/arturdoruch-http/health.svg)

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

###  Alternatives

[kriswallsmith/buzz

Lightweight HTTP client

2.0k31.3M443](/packages/kriswallsmith-buzz)[smi2/phpclickhouse

PHP ClickHouse Client

83510.1M71](/packages/smi2-phpclickhouse)[eightpoints/guzzle-bundle

Integrates Guzzle 6.x, a PHP HTTP Client, into Symfony. Comes with easy and powerful configuration options and optional plugins.

45912.1M55](/packages/eightpoints-guzzle-bundle)[aplus/http-client

Aplus Framework HTTP Client Library

2161.6M1](/packages/aplus-http-client)[aura/http

The Aura HTTP package provides objects to build and send HTTP responses from the server to the client.

7338.8k4](/packages/aura-http)[popphp/pop-http

Pop Http Component for Pop PHP Framework

1018.5k13](/packages/popphp-pop-http)

PHPackages © 2026

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