PHPackages                             fofx/guzzle-middleware - 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. fofx/guzzle-middleware

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

fofx/guzzle-middleware
======================

Enhanced Guzzle client with middleware, debugging, and proxy support.

v1.3.3(7mo ago)011MITPHPPHP ^8.1

Since Sep 21Pushed 7mo ago1 watchersCompare

[ Source](https://github.com/fofxtools/guzzle-middleware)[ Packagist](https://packagist.org/packages/fofx/guzzle-middleware)[ RSS](/packages/fofx-guzzle-middleware/feed)WikiDiscussions master Synced today

READMEChangelogDependencies (7)Versions (35)Used By (0)

FOfX Guzzle Middleware
======================

[](#fofx-guzzle-middleware)

[![Latest Version on Packagist](https://camo.githubusercontent.com/41e24263c846f690d9ff2db39d7acbc658a37ad28a870ac35b9dcf9e90a92638/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f666f66782f67757a7a6c652d6d6964646c65776172652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/fofx/guzzle-middleware)[![Total Downloads](https://camo.githubusercontent.com/af3ef812cf2eba821c73a52115a031a295f5a78555a192143a23b2142f103f02/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f666f66782f67757a7a6c652d6d6964646c65776172652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/fofx/guzzle-middleware)[![License](https://camo.githubusercontent.com/7c27cbb3688f5fcf316fd11d14c41e1679f1171572c0c8d968953890089dbe69/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f666f66782f67757a7a6c652d6d6964646c65776172652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/fofx/guzzle-middleware)

FOfX Guzzle Middleware is an enhanced Guzzle client with middleware, debugging, and proxy support. It provides extended functionality for capturing detailed request and response information, making it easier to debug and log HTTP transactions in your PHP applications.

Features
--------

[](#features)

- Enhanced Guzzle client with middleware support
- Detailed request and response logging
- Debug information capture
- Proxy configuration support
- Easy-to-use interface for making HTTP requests
- Flexible configuration options

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

[](#requirements)

- PHP 8.1 or higher
- Guzzle 7.9 or higher

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

[](#installation)

You can install the package via Composer:

```
composer require fofx/guzzle-middleware
```

Development Server
------------------

[](#development-server)

The package includes a development server for testing and development. Start it before running tests:

```
php -S localhost:8000 public/dev-server.php
```

The dev server provides endpoints for testing:

- `/redirect/{n}` - Redirects n times
- `/error/{code}` - Returns specified HTTP error code
- `/delay/{seconds}` - Delays response
- `/api/test` - Basic test endpoint
- `/api/echo` - Echoes request details

Note: The dev server must be running for unit tests to pass.

Usage
-----

[](#usage)

### Basic Usage

[](#basic-usage)

Here's a simple example of how to use the `MiddlewareClient`:

```
require __DIR__ . '/vendor/autoload.php';

use FOfX\GuzzleMiddleware\MiddlewareClient;

$client = new MiddlewareClient();
$response = $client->makeRequest('GET', 'http://httpbin.org/redirect/2');
print_r($client->getAllTransactions());
```

This should print each transaction in the redirect chain:

```
Array
(
    [0] => Array
        (
            [request] => Array
                (
                    [method] => GET
                    [url] => http://httpbin.org/redirect/2
                    [headers] => {"User-Agent":["GuzzleHttp\/7"],"Host":["httpbin.org"]}
                    [body] =>
                    [protocol] => 1.1
                    [target] => /redirect/2
                )

            [response] => Array
                (
                    [statusCode] => 302
                    [headers] => {"Date":["Mon, 13 Jan 2025 19:03:26 GMT"],"Content-Type":["text\/html; charset=utf-8"],"Content-Length":["247"],"Connection":["keep-alive"],"Server":["gunicorn\/19.9.0"],"Location":["\/relative-redirect\/1"],"Access-Control-Allow-Origin":["*"],"Access-Control-Allow-Credentials":["true"]}
                    [body] => DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
Redirecting...
Redirecting...
You should be redirected automatically to target URL: /relative-redirect/1.  If not click the link.
                    [contentLength] => 247
                    [reasonPhrase] => FOUND
                )

        )

    [1] => Array
        (
            [request] => Array
                (
                    [method] => GET
                    [url] => http://httpbin.org/relative-redirect/1
                    [headers] => {"Host":["httpbin.org"],"User-Agent":["GuzzleHttp\/7"]}
                    [body] =>
                    [protocol] => 1.1
                    [target] => /relative-redirect/1
                )

            [response] => Array
                (
                    [statusCode] => 302
                    [headers] => {"Date":["Mon, 13 Jan 2025 19:03:28 GMT"],"Content-Type":["text\/html; charset=utf-8"],"Content-Length":["0"],"Connection":["keep-alive"],"Server":["gunicorn\/19.9.0"],"Location":["\/get"],"Access-Control-Allow-Origin":["*"],"Access-Control-Allow-Credentials":["true"]}
                    [body] =>
                    [contentLength] => 0
                    [reasonPhrase] => FOUND
                )

        )

    [2] => Array
        (
            [request] => Array
                (
                    [method] => GET
                    [url] => http://httpbin.org/get
                    [headers] => {"Host":["httpbin.org"],"User-Agent":["GuzzleHttp\/7"]}
                    [body] =>
                    [protocol] => 1.1
                    [target] => /get
                )

            [response] => Array
                (
                    [statusCode] => 200
                    [headers] => {"Date":["Mon, 13 Jan 2025 19:03:30 GMT"],"Content-Type":["application\/json"],"Content-Length":["233"],"Connection":["keep-alive"],"Server":["gunicorn\/19.9.0"],"Access-Control-Allow-Origin":["*"],"Access-Control-Allow-Credentials":["true"]}
                    [body] => {
  "args": {},
  "headers": {
    "Host": "httpbin.org",
    "User-Agent": "GuzzleHttp/7",
    "X-Amzn-Trace-Id": "Root=1-67856380-2722bf0639f803eb79d6fd4b"
  },
  "origin": "IP REMOVED",
  "url": "http://httpbin.org/get"
}

                    [contentLength] => 233
                    [reasonPhrase] => OK
                )

        )

)
```

To print just the last transaction, use the `getLastTransaction` method:

```
print_r($client->getLastTransaction());
```

This should print the last transaction.

**Note**: The elements are named 'request' and 'response' instead of '0', '1', etc.

```
Array
(
    [request] => Array
        (
            [method] => GET
            [url] => http://httpbin.org/get
            [headers] => {"Host":["httpbin.org"],"User-Agent":["GuzzleHttp\/7"]}
            [body] =>
            [protocol] => 1.1
            [target] => /get
        )

    [response] => Array
        (
            [statusCode] => 200
            [headers] => {"Date":["Mon, 13 Jan 2025 19:03:30 GMT"],"Content-Type":["application\/json"],"Content-Length":["233"],"Connection":["keep-alive"],"Server":["gunicorn\/19.9.0"],"Access-Control-Allow-Origin":["*"],"Access-Control-Allow-Credentials":["true"]}
            [body] => {
  "args": {},
  "headers": {
    "Host": "httpbin.org",
    "User-Agent": "GuzzleHttp/7",
    "X-Amzn-Trace-Id": "Root=1-67856380-2722bf0639f803eb79d6fd4b"
  },
  "origin": "IP REMOVED",
  "url": "http://httpbin.org/get"
}

            [contentLength] => 233
            [reasonPhrase] => OK
        )

)

```

To print a summary of the transactions, use the `getTransactionSummary` method:

```
print_r($client->getTransactionSummary());
```

This should print a summary of the transactions:

```
Array
(
    [request_methods] => Array
        (
            [0] => GET
            [1] => GET
            [2] => GET
        )

    [request_urls] => Array
        (
            [0] => http://httpbin.org/redirect/2
            [1] => http://httpbin.org/relative-redirect/1
            [2] => http://httpbin.org/get
        )

    [request_protocols] => Array
        (
            [0] => 1.1
            [1] => 1.1
            [2] => 1.1
        )

    [request_targets] => Array
        (
            [0] => /redirect/2
            [1] => /relative-redirect/1
            [2] => /get
        )

    [response_status_codes] => Array
        (
            [0] => 302
            [1] => 302
            [2] => 200
        )

    [response_content_lengths] => Array
        (
            [0] => 247
            [1] => 0
            [2] => 233
        )

    [response_reason_phrases] => Array
        (
            [0] => FOUND
            [1] => FOUND
            [2] => OK
        )

)

```

To print the Guzzle debug stream, use the `getDebug` method:

```
print_r($client->getDebug());
```

This should print the following:

```
Array
(
    [http://httpbin.org/redirect/2] => * Found bundle for host: 0x1ef4ffa2960 [serially]
* Re-using existing connection with host httpbin.org
> GET /get HTTP/1.1
Host: httpbin.org
User-Agent: GuzzleHttp/7

* Request completely sent off
< HTTP/1.1 200 OK
< Date: Mon, 13 Jan 2025 19:03:30 GMT
< Content-Type: application/json
< Content-Length: 233
< Connection: keep-alive
< Server: gunicorn/19.9.0
< Access-Control-Allow-Origin: *
< Access-Control-Allow-Credentials: true
<
* Connection #0 to host httpbin.org left intact
nection #0 to host httpbin.org left intact
edentials: true
<
* Connection #0 to host httpbin.org left intact

)

```

### POST Example

[](#post-example)

To get the last transaction for a POST request, use the `makeRequest` method with the `POST` method:

```
$client = new MiddlewareClient();
$response = $client->makeRequest('POST', 'http://localhost:8000/api/post', [
    'form_params' => ['username' => 'testuser', 'password' => 'secret123']
]);
print_r($client->getLastTransaction());
```

### Using the `makeMiddlewareRequest` Function

[](#using-the-makemiddlewarerequest-function)

Alternatively, you can use the `makeMiddlewareRequest` function for an alternative approach. See [examples/makeMiddlewareRequest.php](examples/makeMiddlewareRequest.php).

```
require __DIR__ . '/../vendor/autoload.php';

use FOfX\GuzzleMiddleware;
use FOfX\GuzzleMiddleware\MiddlewareClient;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Monolog\Level;

// Create Monolog logger with stdout handler
$logger = new Logger('guzzle-middleware');
$logger->pushHandler(new StreamHandler('php://stdout', Level::Info));

// Create a new MiddlewareClient instance with logger
$client = new MiddlewareClient([], $logger);

$config = [];
$options = [];
$rotateUserAgent = false;

// Make a request to local dev server
$result = GuzzleMiddleware\makeMiddlewareRequest('GET', 'http://httpbin.org/redirect/2', $config, $options, $logger, $rotateUserAgent);
print_r($result);
```

Documentation
-------------

[](#documentation)

Detailed documentation can be found in the `docs` folder:

- [Example Outputs](docs/example-outputs.md) - Shows sample outputs from key methods like getAllTransactions(), getLastTransaction(), getTransactionSummary(), and getDebug() when handling redirect chains
- [Middleware Algorithm](docs/middleware-algorithm.md) - Explains the algorithm used to handle redirects and other middleware
- [Middleware Flow](docs/middleware-flow.mmd) - A sequence diagram showing the flow of the MiddlewareClient
- [Middleware Structure](docs/middleware-structure.mmd) - A Mermaid markdown diagram showing the structure of the MiddlewareClient

Configuration Options
---------------------

[](#configuration-options)

The `MiddlewareClient` constructor accepts the following parameters:

- `$config` (array): Guzzle configuration options
- `$logger` (LoggerInterface): A PSR-3 compatible logger
- `$proxyConfig` (array): Proxy configuration options

### Proxy Configuration

[](#proxy-configuration)

To use a proxy with the MiddlewareClient:

```
$proxyConfig = ['proxy' => 'http://proxy.example.com:8000'];
$client = new MiddlewareClient(proxyConfig: $proxyConfig);
```

Testing and Development
-----------------------

[](#testing-and-development)

Remember to start the development server before running tests.

To run the PHPUnit test suite through composer:

```
composer test
```

To use PHPStan for static analysis:

```
composer phpstan
```

To use PHP-CS-Fixer for code style:

```
composer cs-fix
```

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

Credits
-------

[](#credits)

- [fofx](https://github.com/fofxtools)

This package is built on top of [Guzzle](https://github.com/guzzle/guzzle), a PHP HTTP client library.

###  Health Score

37

—

LowBetter than 81% of packages

Maintenance65

Regular maintenance activity

Popularity5

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity60

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 ~13 days

Recently: every ~81 days

Total

34

Last Release

212d ago

PHP version history (2 changes)v1.0.0PHP ^8.0

v1.0.9PHP ^8.1

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/6767029?v=4)[fofx](/maintainers/fofx)[@fofx](https://github.com/fofx)

---

Top Contributors

[![fofxtools](https://avatars.githubusercontent.com/u/177870764?v=4)](https://github.com/fofxtools "fofxtools (34 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/fofx-guzzle-middleware/health.svg)

```
[![Health](https://phpackages.com/badges/fofx-guzzle-middleware/health.svg)](https://phpackages.com/packages/fofx-guzzle-middleware)
```

###  Alternatives

[laravel/framework

The Laravel Framework.

34.8k543.8M20.1k](/packages/laravel-framework)[tempest/framework

The PHP framework that gets out of your way.

2.2k34.4k15](/packages/tempest-framework)[drupal/core

Drupal is an open source content management platform powering millions of websites and applications.

21866.0M1.7k](/packages/drupal-core)[drupal/core-recommended

Locked core dependencies; require this project INSTEAD OF drupal/core.

6942.5M421](/packages/drupal-core-recommended)[civicrm/civicrm-core

Open source constituent relationship management for non-profits, NGOs and advocacy organizations.

751291.4k43](/packages/civicrm-civicrm-core)[avalara/avataxclient

Client library for Avalara's AvaTax suite of business tax calculation and processing services. Uses the REST v2 API.

528.5M7](/packages/avalara-avataxclient)

PHPackages © 2026

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