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(5mo ago)011MITPHPPHP ^8.1

Since Sep 21Pushed 5mo 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 1mo ago

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

40

—

FairBetter than 87% of packages

Maintenance77

Regular maintenance activity

Popularity5

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity59

Maturing project, gaining track record

 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

156d ago

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

v1.0.9PHP ^8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/b70d3faff89e2b6642ccb6f5282a03c1fa6260bf991c14d9c4abf7822c8181c6?d=identicon)[fofx](/maintainers/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

[shopify/shopify-api

Shopify API Library for PHP

4634.8M16](/packages/shopify-shopify-api)[akamai-open/edgegrid-client

Implements the Akamai {OPEN} EdgeGrid Authentication specified by https://developer.akamai.com/introduction/Client\_Auth.html

482.5M6](/packages/akamai-open-edgegrid-client)[api-platform/metadata

API Resource-oriented metadata attributes and factories

223.5M96](/packages/api-platform-metadata)[muhammadhuzaifa/telescope-guzzle-watcher

Telescope Guzzle Watcher provide a custom watcher for intercepting http requests made via guzzlehttp/guzzle php library. The package uses the on\_stats request option for extracting the request/response data. The watcher intercept and log the request into the Laravel Telescope HTTP Client Watcher.

98239.8k1](/packages/muhammadhuzaifa-telescope-guzzle-watcher)[phpro/http-tools

HTTP tools for developing more consistent HTTP implementations.

28137.8k](/packages/phpro-http-tools)[mimmi20/browser-detector

Library to detect Browsers and Devices

48153.5k3](/packages/mimmi20-browser-detector)

PHPackages © 2026

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