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

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

ctw/ctw-http
============

This package provides utility classes and constants to facilitate common operations of PSR-7 and a group of exceptions which represent HTTP status codes.

4.0.6(5mo ago)1125.8k—8.2%15BSD-3-ClausePHPPHP ^8.3CI passing

Since Mar 10Pushed 5mo ago1 watchersCompare

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

READMEChangelogDependencies (4)Versions (50)Used By (5)

Package "ctw/ctw-http"
======================

[](#package-ctwctw-http)

[![Latest Stable Version](https://camo.githubusercontent.com/e980379d02e2951ecfdbff8c09a7e1e01a9b449a6ea0f79d2693e921eb379ef1/68747470733a2f2f706f7365722e707567782e6f72672f6374772f6374772d687474702f762f737461626c65)](https://packagist.org/packages/ctw/ctw-http)[![GitHub Actions](https://github.com/jonathanmaron/ctw-http/actions/workflows/tests.yml/badge.svg)](https://github.com/jonathanmaron/ctw-http/actions/workflows/tests.yml)[![Scrutinizer Build](https://camo.githubusercontent.com/bcfc49cc2bc775ff6ea87d98fba0031090a809bd45deb5f883c70e33f16ae895/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6a6f6e617468616e6d61726f6e2f6374772d687474702f6261646765732f6275696c642e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/jonathanmaron/ctw-http/build-status/master)[![Scrutinizer Quality](https://camo.githubusercontent.com/ba8fabdfe8e4e526d64acdf1a1e5e1fde7ef6d8e120b45f818cd1a30da627d42/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6a6f6e617468616e6d61726f6e2f6374772d687474702f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/jonathanmaron/ctw-http/?branch=master)[![Code Coverage](https://camo.githubusercontent.com/fc1ac1e4ca56d34aac76746469da3da8b9398603a593159579c3f390c87996aa/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6a6f6e617468616e6d61726f6e2f6374772d687474702f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/jonathanmaron/ctw-http/?branch=master)

Utility classes, constants, and typed exceptions for PSR-7 HTTP operations, providing a complete HTTP status code registry with metadata and throwable exceptions for all 4xx/5xx status codes.

Introduction
------------

[](#introduction)

### Why This Library Exists

[](#why-this-library-exists)

Working with HTTP in PHP often involves scattered magic numbers, inconsistent error handling, and repetitive exception creation. The PSR-7 standard defines message interfaces but doesn't provide status code constants, metadata, or exception types.

This library provides a complete HTTP toolkit:

- **Status code constants**: All standard HTTP status codes as class constants
- **Method constants**: HTTP method names (GET, POST, PUT, DELETE, etc.)
- **Status metadata**: Human-readable names, descriptions, and documentation URLs
- **Typed exceptions**: Dedicated exception classes for every 4xx and 5xx status code
- **Exception hierarchy**: Catch client errors (4xx) or server errors (5xx) separately

### Problems This Library Solves

[](#problems-this-library-solves)

1. **Magic numbers**: Code uses `404` instead of readable `STATUS_NOT_FOUND`
2. **Inconsistent exceptions**: Each project invents its own HTTP exception classes
3. **Missing metadata**: Status codes lack human-readable descriptions
4. **Catch-all handling**: No way to catch only client errors vs. server errors
5. **Documentation gaps**: Developers must look up status code meanings externally

### Where to Use This Library

[](#where-to-use-this-library)

- **PSR-7 applications**: Enhance HTTP message handling with typed constants
- **API development**: Throw semantically correct HTTP exceptions
- **Error handling middleware**: Catch exceptions by category (client/server)
- **Logging and monitoring**: Include status metadata in error reports
- **HTTP clients**: Use constants instead of magic numbers

### Design Goals

[](#design-goals)

1. **PSR-7 aligned**: Implements `Fig\Http\Message\StatusCodeInterface`
2. **Complete coverage**: All standard HTTP status codes (1xx through 5xx)
3. **Rich metadata**: Name, phrase, and documentation URL for each status
4. **Exception hierarchy**: Abstract base classes for client (4xx) and server (5xx) errors
5. **Type-safe**: Full strict types and interface contracts

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

[](#requirements)

- PHP 8.3 or higher
- fig/http-message-util ^1.1

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

[](#installation)

Install by adding the package as a [Composer](https://getcomposer.org) requirement:

```
composer require ctw/ctw-http
```

Usage Examples
--------------

[](#usage-examples)

### HTTP Status Metadata

[](#http-status-metadata)

Retrieve complete metadata for any status code:

```
use Ctw\Http\HttpStatus;

$httpStatus = new HttpStatus(HttpStatus::STATUS_NOT_FOUND);
$entity = $httpStatus->get();

// Returns:
// Ctw\Http\Entity\HttpStatus {
//   +statusCode: 404
//   +name: "Not Found"
//   +phrase: "The requested resource could not be found but may be available again in the future."
//   +exception: "Ctw\Http\HttpException\NotFoundException"
//   +url: "https://httpstatuses.com/404"
// }
```

### Throwing HTTP Exceptions

[](#throwing-http-exceptions)

Each 4xx and 5xx status code has a dedicated exception class:

```
use Ctw\Http\HttpException;

// Default message uses status name
throw new HttpException\NotFoundException();
// "404 Not Found"

// Custom message
throw new HttpException\NotFoundException('User with ID 123 not found');
// "User with ID 123 not found"

// With custom headers
throw new HttpException\UnauthorizedException(
    message: 'Invalid API key',
    headers: ['WWW-Authenticate' => 'Bearer']
);
```

### Catching Exceptions by Category

[](#catching-exceptions-by-category)

The exception hierarchy allows catching by error category:

```
use Ctw\Http\HttpException;

try {
    // Application code
} catch (HttpException\AbstractClientErrorException $e) {
    // Handle 4xx errors (client's fault)
    $statusCode = $e->getStatusCode();
    $headers = $e->getHeaders();
} catch (HttpException\AbstractServerErrorException $e) {
    // Handle 5xx errors (server's fault)
}

// Or catch all HTTP exceptions
try {
    // Application code
} catch (HttpException\HttpExceptionInterface $e) {
    // Handle any HTTP exception
}
```

### Exception Hierarchy

[](#exception-hierarchy)

```
HttpExceptionInterface
└── AbstractException
    ├── AbstractClientErrorException (4xx)
    │   ├── BadRequestException (400)
    │   ├── UnauthorizedException (401)
    │   ├── ForbiddenException (403)
    │   ├── NotFoundException (404)
    │   └── ... (all 4xx codes)
    └── AbstractServerErrorException (5xx)
        ├── InternalServerErrorException (500)
        ├── NotImplementedException (501)
        ├── BadGatewayException (502)
        ├── ServiceUnavailableException (503)
        └── ... (all 5xx codes)

```

### HTTP Method Constants

[](#http-method-constants)

```
use Ctw\Http\HttpMethod;

HttpMethod::METHOD_GET;      // 'GET'
HttpMethod::METHOD_POST;     // 'POST'
HttpMethod::METHOD_PUT;      // 'PUT'
HttpMethod::METHOD_PATCH;    // 'PATCH'
HttpMethod::METHOD_DELETE;   // 'DELETE'
HttpMethod::METHOD_HEAD;     // 'HEAD'
HttpMethod::METHOD_OPTIONS;  // 'OPTIONS'
HttpMethod::METHOD_CONNECT;  // 'CONNECT'
HttpMethod::METHOD_TRACE;    // 'TRACE'
HttpMethod::METHOD_PURGE;    // 'PURGE'
```

### HTTP Status Constants

[](#http-status-constants)

```
use Ctw\Http\HttpStatus;

// Informational (1xx)
HttpStatus::STATUS_CONTINUE;              // 100
HttpStatus::STATUS_SWITCHING_PROTOCOLS;   // 101

// Success (2xx)
HttpStatus::STATUS_OK;                    // 200
HttpStatus::STATUS_CREATED;               // 201
HttpStatus::STATUS_ACCEPTED;              // 202
HttpStatus::STATUS_NO_CONTENT;            // 204

// Redirection (3xx)
HttpStatus::STATUS_MOVED_PERMANENTLY;     // 301
HttpStatus::STATUS_FOUND;                 // 302
HttpStatus::STATUS_NOT_MODIFIED;          // 304
HttpStatus::STATUS_TEMPORARY_REDIRECT;    // 307
HttpStatus::STATUS_PERMANENT_REDIRECT;    // 308

// Client Error (4xx)
HttpStatus::STATUS_BAD_REQUEST;           // 400
HttpStatus::STATUS_UNAUTHORIZED;          // 401
HttpStatus::STATUS_FORBIDDEN;             // 403
HttpStatus::STATUS_NOT_FOUND;             // 404
HttpStatus::STATUS_METHOD_NOT_ALLOWED;    // 405
HttpStatus::STATUS_CONFLICT;              // 409
HttpStatus::STATUS_UNPROCESSABLE_ENTITY;  // 422
HttpStatus::STATUS_TOO_MANY_REQUESTS;     // 429

// Server Error (5xx)
HttpStatus::STATUS_INTERNAL_SERVER_ERROR; // 500
HttpStatus::STATUS_NOT_IMPLEMENTED;       // 501
HttpStatus::STATUS_BAD_GATEWAY;           // 502
HttpStatus::STATUS_SERVICE_UNAVAILABLE;   // 503
HttpStatus::STATUS_GATEWAY_TIMEOUT;       // 504
```

### Available Exception Classes

[](#available-exception-classes)

StatusException Class400`BadRequestException`401`UnauthorizedException`402`PaymentRequiredException`403`ForbiddenException`404`NotFoundException`405`MethodNotAllowedException`406`NotAcceptableException`407`ProxyAuthenticationRequiredException`408`RequestTimeoutException`409`ConflictException`410`GoneException`411`LengthRequiredException`412`PreconditionFailedException`413`PayloadTooLargeException`414`RequestUriTooLongException`415`UnsupportedMediaTypeException`416`RangeNotSatisfiableException`417`ExpectationFailedException`418`ImATeapotException`421`MisdirectedRequestException`422`UnprocessableEntityException`423`LockedException`424`FailedDependencyException`425`TooEarlyException`426`UpgradeRequiredException`428`PreconditionRequiredException`429`TooManyRequestsException`431`RequestHeaderFieldsTooLargeException`451`UnavailableForLegalReasonsException`500`InternalServerErrorException`501`NotImplementedException`502`BadGatewayException`503`ServiceUnavailableException`504`GatewayTimeoutException`505`VersionNotSupportedException`506`VariantAlsoNegotiatesException`507`InsufficientStorageException`508`LoopDetectedException`510`NotExtendedException`511`NetworkAuthenticationRequiredException`

###  Health Score

54

—

FairBetter than 97% of packages

Maintenance70

Regular maintenance activity

Popularity34

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity81

Battle-tested with a long release history

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

Recently: every ~1 days

Total

49

Last Release

175d ago

Major Versions

1.0.15 → 2.0.02022-02-13

2.0.0 → 3.0.02022-07-07

3.0.23 → 4.0.02024-06-18

PHP version history (4 changes)1.0.1PHP ^7.4 || ^8.0

3.0.0PHP ^8.0

3.0.11PHP ^8.1

4.0.0PHP ^8.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/18d8bc9bdee8ab1b0cfccce6a06d2438acbed3a58b0046c4834c5678f6769342?d=identicon)[jonathanmaron](/maintainers/jonathanmaron)

---

Top Contributors

[![jonathanmaron](https://avatars.githubusercontent.com/u/298462?v=4)](https://github.com/jonathanmaron "jonathanmaron (86 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[react/http

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

78026.4M414](/packages/react-http)[mezzio/mezzio

PSR-15 Middleware Microframework

3883.6M97](/packages/mezzio-mezzio)[laminas/laminas-stratigility

PSR-7 middleware foundation for building and dispatching middleware pipelines

586.6M81](/packages/laminas-laminas-stratigility)[mezzio/mezzio-router

Router subcomponent for Mezzio

265.0M61](/packages/mezzio-mezzio-router)[bitrix24/b24phpsdk

An official PHP library for the Bitrix24 REST API

9230.2k4](/packages/bitrix24-b24phpsdk)[sunrise/http-router

A powerful solution as the foundation of your project.

16249.8k10](/packages/sunrise-http-router)

PHPackages © 2026

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