PHPackages                             joefallon/phphttp - 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. joefallon/phphttp

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

joefallon/phphttp
=================

Library of simple HTTP utilities.

v3.0.1(8mo ago)045MITPHPPHP &gt;=7.4.0

Since Oct 29Pushed 8mo ago1 watchersCompare

[ Source](https://github.com/joefallon/phphttp)[ Packagist](https://packagist.org/packages/joefallon/phphttp)[ Docs](https://github.com/joefallon/phphttp)[ RSS](/packages/joefallon-phphttp/feed)WikiDiscussions master Synced today

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

phphttp — Small, dependency-free HTTP utilities for PHP
=======================================================

[](#phphttp--small-dependency-free-http-utilities-for-php)

Simple, focused helpers for common HTTP tasks: user-agent parsing, mime-type lookup, safe redirects, and HTTP status messages. Designed to be tiny, well-tested, and easy to drop into any PHP project.

- Package: joefallon/phphttp
- Author: Joe Fallon
- License: MIT
- PHP: &gt;= 7.4

> Why this library?
>
> Many projects reimplement small HTTP utilities (parsing UA strings, mapping file extensions to MIME types, performing safe redirects). phphttp provides a compact, well-documented, and thoroughly-tested set of utilities so you can stop reinventing the wheel and focus on your application's logic.

Table of contents

- Features
- Installation
- Quick start
- Examples
    - Agent (user-agent parsing)
    - MimeType (file extension -&gt; MIME)
    - HttpCodes (status message lookup)
    - PageRedirect (safe redirects)
- API reference
- Testing
- Contributing
- Support &amp; Security
- License

Features
--------

[](#features)

- Lightweight, dependency-free utilities (PSR-4 autoloading only)
- Deterministic, unit-tested parsing for user agents
- Robust mime-type lookup from filenames and extensions (handles edge cases)
- Secure redirect helper with host whitelist and header-injection protection
- Clear API and small surface area — easy to understand and audit

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

[](#installation)

Install via Composer (recommended):

```
composer require joefallon/phphttp
```

Requirements

- PHP 7.4 or newer
- Composer for installation

Autoloading

The package uses PSR-4 autoloading (namespace `JoeFallon\`). After installing via Composer you can use the Composer autoloader as usual:

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

Quick start
-----------

[](#quick-start)

Here's a short tour of the four primary utilities included in this package.

- `Agent` — lightweight user-agent parser (browser, mobile, robot, platform, languages)
- `MimeType` — map filenames or extensions to MIME types
- `HttpCodes` — get human-friendly messages for HTTP status codes
- `PageRedirect` — perform safe, testable redirects with host whitelisting

Examples
--------

[](#examples)

The examples below show typical usage; they assume Composer autoloading is enabled.

Agent — parse a user-agent string

```
use JoeFallon\PhpHttp\Agent;

$ua = 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 ' .
      '(KHTML, like Gecko) Version/16.0 Mobile/15E148 Safari/604.1';
$headers = [
    'HTTP_ACCEPT_LANGUAGE' => 'en-US,en;q=0.9',
    'HTTP_ACCEPT_CHARSET'  => 'utf-8',
    'HTTP_REFERER'         => '',
];

$agent = new Agent($ua, $headers);

if ($agent->isMobile()) {
    echo "Mobile: " . $agent->getMobileDeviceName() . "\n";
}

echo "Browser: " . $agent->getBrowserName() . " " . $agent->getBrowserVersion() . "\n";
echo "Platform: " . $agent->getPlatformName() . "\n";

// Languages/charsets
$languages = $agent->getLanguages();
$charsets = $agent->getCharsets();
```

Notes

- `Agent` accepts an optional user-agent string and headers array so you can unit-test parsing without touching `$_SERVER`.
- Methods: `isBrowser()`, `isMobile()`, `isRobot()`, `isReferral()`, `getBrowserName()`, `getBrowserVersion()`, `getMobileDeviceName()`, `getRobotName()`, `getPlatformName()`, `getReferrer()`, `getAgentString()`, `getLanguages()`, `getCharsets()`, `acceptsLang()`, `acceptsCharset()`.

MimeType — resolve MIME types from filenames or extensions

```
use JoeFallon\PhpHttp\MimeType;

// Static convenience
printf("%s\n", MimeType::forFileName('image.png')); // image/png
printf("%s\n", MimeType::forExtension('.jpg'));    // image/jpeg

// Instance compatibility
$m = new MimeType();
echo $m->getMimeTypeFromFileName('document.pdf'); // application/pdf
```

Why this is robust

- Handles spaces, path segments, Windows backslashes, and null bytes in filenames by design.
- Returns a sensible default (`application/octet-stream`) when the extension is unknown.

HttpCodes — human-friendly messages for status codes

```
use JoeFallon\PhpHttp\HttpCodes;

echo HttpCodes::getCodeMessage(404); // "Not Found"
```

This helper is a tiny convenience for rendering status messages in error pages or logs.

PageRedirect — safe, testable redirects

```
use JoeFallon\PhpHttp\PageRedirect;

// Simple relative redirect (default)
$r = new PageRedirect('/welcome');
// Will send a 302 Location header by default when redirect() is called
// $r->redirect();

// External redirects require opt-in hostname whitelist
$r2 = new PageRedirect('https://example.com/welcome');
$r2->setAllowedHosts(['example.com']);

// In tests inject a sender to avoid calling header()/exit()
$r2->setSender(function(string $location, int $status) {
    // record call, assert values in tests
    // e.g. $this->assertEquals('https://example.com/welcome', $location);
});

// Validate before redirecting
if ($r2->isSafeRedirect()) {
    $r2->redirect(301);
}
```

Security notes

- `PageRedirect` strips NUL/CR/LF from destinations to prevent header injection.
- By default absolute URLs are disallowed until you explicitly whitelist hosts with `setAllowedHosts()`.

API reference
-------------

[](#api-reference)

This section lists the most commonly-used public methods. See source for full details and docblocks.

Agent (namespace: `JoeFallon\PhpHttp`)

- \_\_construct(?string $agentString = null, ?array $headers = null)
- isBrowser(): bool
- isMobile(): bool
- isRobot(): bool
- isReferral(): bool
- getBrowserName(): string
- getBrowserVersion(): string
- getMobileDeviceName(): string
- getRobotName(): string
- getPlatformName(): string
- getReferrer(): string
- getAgentString(): string
- getLanguages(): string\[\]
- getCharsets(): string\[\]
- acceptsLang(string $lang = 'en'): bool
- acceptsCharset(string $charset = 'utf-8'): bool

MimeType (namespace: `JoeFallon\PhpHttp`)

- forFileName(string $filename = ''): string
- forExtension(string $extension = ''): string
- getMimeTypeFromFileName(string $filename = ''): string (instance wrapper)
- getMimeTypeFromFileExtension(string $extension = ''): string (instance wrapper)

HttpCodes (namespace: `JoeFallon\PhpHttp`)

- getCodeMessage(int $code): string

PageRedirect (namespace: `JoeFallon\PhpHttp`)

- \_\_construct(string $destination = '/', callable $sender = null)
- getRedirectDestination(): string
- setRedirectDestination(string $destination): void
- setAllowedHosts(array $hosts): void
- setSender(callable $sender): void
- isSafeRedirect(): bool
- redirect(int $status = 302): void

Testing
-------

[](#testing)

This repository includes a comprehensive unit test suite. Tests are now written for PHPUnit 9.6 (compatible with PHP 7.4 through PHP 8.2).

Run tests locally (after `composer install`):

```
# Install dependencies (if not installed)
composer install --no-interaction --prefer-dist

# Run the full test suite using the project's configuration
./vendor/bin/phpunit -c phpunit.xml.dist
```

Run a single test file for focused feedback:

```
./vendor/bin/phpunit -c phpunit.xml.dist tests/JoeFallon/PhpHttp/AgentTests.php -v
```

Notes

- The test bootstrap (`tests/bootstrap.php`) loads Composer's autoloader and `tests/config/main.php`.
- Tests are written to be deterministic and avoid relying on `$_SERVER` where possible.
- PHPUnit 9.6 is the chosen test runner because it is the last PHPUnit release that supports PHP 7.4. The suite also runs under newer PHP versions (e.g., PHP 8.2) for development convenience, but CI should include PHP 7.4 where possible to ensure compatibility.

CI

A GitHub Actions workflow is included to run the test suite on PHP 7.4 and PHP 8.2. See `.github/workflows/phpunit.yml` for details.

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

[](#contributing)

Contributions are welcome! A good contribution path:

1. Open an issue describing the change you want to make.
2. Fork the repository and create a feature branch.
3. Add tests that cover your change.
4. Submit a pull request with a clear description and rationale.

Coding guidelines

- Keep the API surface small and backward-compatible.
- Add unit tests for bug fixes and new behavior.
- Follow PSR-12 coding style where practical.

Support &amp; Security
----------------------

[](#support--security)

For security-sensitive issues (e.g. potential header injection bugs) please open a private issue on the repository or email the author at the address in `composer.json`.

For general questions or help, open an issue on GitHub.

License
-------

[](#license)

This project is licensed under the MIT License. See the `LICENSE` file for details.

---

Contact

If you have questions or need help integrating phphttp, open an issue on GitHub:

---

**Built with ❤️ and the KISS principle.**

###  Health Score

38

—

LowBetter than 83% of packages

Maintenance59

Moderate activity, may be stable

Popularity8

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity67

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

Total

5

Last Release

264d ago

Major Versions

v1.0.0 → v2.0.02014-12-09

v2.0.2 → v3.0.12025-10-12

PHP version history (2 changes)v1.0.0PHP &gt;=5.3.0

v3.0.1PHP &gt;=7.4.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/97cecfa80ffec8e9e7b5d0ff6df026b636e31a15fe0c2155baba402b5d4f0819?d=identicon)[joefallon](/maintainers/joefallon)

---

Top Contributors

[![joefallon](https://avatars.githubusercontent.com/u/4212989?v=4)](https://github.com/joefallon "joefallon (11 commits)")

---

Tags

php

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/joefallon-phphttp/health.svg)

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

###  Alternatives

[hannesvdvreken/guzzle-debugbar

A Guzzle middleware that logs requests to debugbar's timeline

77428.9k2](/packages/hannesvdvreken-guzzle-debugbar)

PHPackages © 2026

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