joefallon/phphttp

Library of simple HTTP utilities.

Installs: 45

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 1

Forks: 0

Open Issues: 0

pkg:composer/joefallon/phphttp

v3.0.1 2025-10-12 22:15 UTC

This package is auto-updated.

Last update: 2025-10-12 22:17:39 UTC


README

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.

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 -> MIME)
    • HttpCodes (status message lookup)
    • PageRedirect (safe redirects)
  • API reference
  • Testing
  • Contributing
  • Support & Security
  • License

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

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

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

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

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

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

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 & 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

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: https://github.com/joefallon/phphttp

Built with ❤️ and the KISS principle.