HttpClient
in package
Modern HTTP Client with cURL Backend and Comprehensive Request Support
Static HTTP client providing secure, configurable web requests with full RESTful method support, automatic performance monitoring, request/response debugging, and optional mocking capabilities. Built on cURL with enterprise-grade security and monitoring features.
Key Features
- RESTful Methods: Complete support for GET, POST, PUT, DELETE, and custom HTTP methods
- JSON Integration: Native JSON encoding with automatic Content-Type header management
- Security First: Basic auth, Bearer tokens, custom headers with secure defaults
- Performance Monitoring: Automatic Timer integration via HttpResult for request tracking
- Debug Support: Verbose cURL logging, response inspection, and request replay tools
- Test-Friendly: Built-in mocking system for unit testing and development
- Configuration Driven: Flexible request configuration via HttpClientConfig objects
Request Flow Architecture
- Method Call: Developer calls static method (get, post, etc.)
- Configuration: HttpClientConfig provides headers, auth, timeouts
- HttpResult Creation: Automatic timer start and request tracking
- cURL Execution: Secure HTTP request with comprehensive error handling
- Response Processing: Headers, body, and metadata captured in HttpResult
- Performance Tracking: Timer stopped with detailed metrics collection
Security Features
- Secure Defaults: HTTPS preferred, secure authentication handling
- Header Management: Case-insensitive header handling with duplicate support
- Authentication: HTTP Basic Auth and OAuth2 Bearer token support
- Request Isolation: Each request isolated with separate configuration
- Error Handling: Comprehensive cURL error capture without information leakage
Usage Patterns
// Simple GET request
$result = HttpClient::get('https://api.example.com/users');
// POST with authentication
$config = new HttpClientConfig('api_request');
$config->bearerToken('abc123');
$result = HttpClient::postJson('https://api.example.com/users', $userData, $config);
// Advanced configuration
$config = new HttpClientConfig();
$config->timeout(60);
$config->setBasicAuth('user', 'pass');
$config->addHeader('X-Custom', 'value');
$result = HttpClient::put('https://api.example.com/resource/123', $data, $config);
Performance and Debugging
- HttpResult objects automatically track request timing via Timer integration
- Verbose logging captures complete cURL communication for troubleshooting
- Request/response inspection available through HttpResult methods
- Last request always accessible via lastHttpResult() for debugging
Testing and Mocking
- Complete request mocking via fakeResponder() for unit tests
- Mock responses return proper HttpResult objects for compatibility
- EventManager integration for request lifecycle monitoring
- Legacy utilities for cURL command generation and file downloads
Tags
Table of Contents
Properties
- $lastHttpResult : HttpResult|null
- Most recently executed HTTP request result for debugging and inspection
- $fakeResponder : callable|null
- Optional mock response handler for testing and development
Methods
- buildCurlCommand() : string
- Generate equivalent cURL command line for debugging and testing purposes
- delete() : HttpResult
- Execute HTTP DELETE request to remove resource from remote endpoint
- downloadToFile() : bool
- Download file from URL directly to local filesystem using cURL
- fakeResponder() : void
- Configure mock response handler for testing and development
- get() : HttpResult
- Execute HTTP GET request to retrieve data from remote endpoint
- lastHttpResult() : HttpResult
- Retrieve the most recent HttpResult object for debugging and inspection
- post() : HttpResult
- Execute HTTP POST request to send data to remote endpoint
- postJson() : HttpResult
- Execute HTTP POST request with automatic JSON encoding and headers
- put() : HttpResult
- Execute HTTP PUT request to update or create resource at specific endpoint
- request() : HttpResult
- Core HTTP request implementation using cURL
Properties
$lastHttpResult
Most recently executed HTTP request result for debugging and inspection
public
static HttpResult|null
$lastHttpResult
= null
Automatically populated with HttpResult object from each HTTP request. Provides access to last request details without requiring explicit result storage. Useful for debugging, logging, and post-request analysis.
Tags
$fakeResponder
Optional mock response handler for testing and development
protected
static callable|null
$fakeResponder
= null
When configured, this callable intercepts all HTTP requests and returns mock HttpResult objects instead of performing real network requests. Essential for unit testing and development environments requiring predictable API responses.
Signature: function(string $method, string $url, mixed $payload, HttpClientConfig $config): HttpResult
Tags
Methods
buildCurlCommand()
Generate equivalent cURL command line for debugging and testing purposes
public
static buildCurlCommand(string $url, array<string|int, string> $headers, mixed $payload) : string
Legacy utility that constructs shell-safe cURL command equivalent to HttpClient request parameters. Useful for debugging, documentation, and manual request testing outside of PHP environment.
Command Generation
- Escapes all arguments for shell safety using escapeshellarg()
- Includes headers with -H flags
- Handles payload data with -d flag
- Uses POST method by default (legacy behavior)
- Generates executable command for terminal use
Parameters
- $url : string
-
Target URL for the cURL command
- $headers : array<string|int, string>
-
Raw header strings (e.g., "Content-Type: application/json")
- $payload : mixed
-
Request body data (string or array)
Tags
Return values
string —Shell-safe cURL command equivalent to request parameters
delete()
Execute HTTP DELETE request to remove resource from remote endpoint
public
static delete(string $url[, HttpClientConfig|null $config = null ]) : HttpResult
Performs idempotent DELETE request to remove specified resource. No request body is typically sent with DELETE requests per REST conventions, though some APIs may accept additional parameters via query string or headers.
REST Semantics
- Resource Removal: Delete specified resource from server
- Idempotent: Multiple identical requests should have same result
- No Payload: DELETE requests typically don't include request body
- Status Codes: Usually returns 200, 204, or 404 depending on API design
Parameters
- $url : string
-
Target resource URL to delete
- $config : HttpClientConfig|null = null
-
Optional configuration (typically for auth/headers)
Tags
Return values
HttpResult —Response confirmation with status code and any returned data
downloadToFile()
Download file from URL directly to local filesystem using cURL
public
static downloadToFile(string $url, string $destPath) : bool
Legacy utility for simple file downloads without the full HttpClient/HttpResult overhead. Writes downloaded content directly to specified file path using cURL file stream handling for memory-efficient large file downloads.
Download Features
- Memory Efficient: Streams directly to file without loading into memory
- Redirect Following: Automatically follows HTTP redirects (FOLLOWLOCATION)
- Timeout Protection: 30-second timeout to prevent hung downloads
- Overwrite Behavior: Target file is overwritten if it exists
- Simple Error Handling: Returns boolean success/failure status
Use Cases
- Quick file downloads in utility scripts
- Backup and synchronization tools
- Asset downloads for applications
- Simple file retrieval without response analysis needs
Parameters
- $url : string
-
Source URL to download from
- $destPath : string
-
Local filesystem path for downloaded file (will be overwritten)
Tags
Return values
bool —True if download completed successfully, false on any error
fakeResponder()
Configure mock response handler for testing and development
public
static fakeResponder(callable|null $callback) : void
Installs or removes a callable that intercepts all HTTP requests made by HttpClient. When active, the mock handler receives request details and must return a properly configured HttpResult object. Essential for unit testing APIs without network dependencies.
Mock Handler Signature
function(string $method, string $url, mixed $payload, HttpClientConfig $config): HttpResult
Handler Responsibilities
- Create HttpResult with provided config
- Set appropriate response data, headers, and status
- Call stopTimer() to complete performance tracking
- Return properly configured HttpResult object
EventManager Integration
Fires 'HttpClient.request.CallingFakeResponder' event when mock handler is invoked.
Parameters
- $callback : callable|null
-
Mock handler function or null to disable mocking
Tags
get()
Execute HTTP GET request to retrieve data from remote endpoint
public
static get(string $url[, HttpClientConfig|null $config = null ]) : HttpResult
Performs idempotent GET request to specified URL with optional configuration. Automatically creates HttpResult with Timer integration for performance monitoring. No request body is sent with GET requests per HTTP standard.
Parameters
- $url : string
-
Target URL to request (must include protocol: http:// or https://)
- $config : HttpClientConfig|null = null
-
Optional request configuration (headers, auth, timeouts)
Tags
Return values
HttpResult —Complete response object with body, headers, timing, and metadata
lastHttpResult()
Retrieve the most recent HttpResult object for debugging and inspection
public
static lastHttpResult() : HttpResult
Returns the HttpResult from the last HTTP request made by any HttpClient method. Useful for post-request analysis, debugging, and accessing detailed request metadata without storing HttpResult objects explicitly.
Use Cases
- Debugging: Inspect failed requests without complex error handling
- Logging: Access detailed request/response data for audit trails
- Testing: Verify request details in unit tests and integration tests
- Performance Analysis: Review timing and cURL metadata after requests
Tags
Return values
HttpResult —Last executed request result or null if no requests made
post()
Execute HTTP POST request to send data to remote endpoint
public
static post(string $url[, mixed|null $payload = null ][, HttpClientConfig|null $config = null ]) : HttpResult
Performs POST request with optional payload to create resources or submit data. Supports multiple payload formats including strings, arrays, and file uploads. Automatically configures cURL options based on payload type.
Payload Handling
- String payloads: Sent as-is with Content-Type from headers
- Array payloads: URL-encoded for form submissions or multipart for file uploads
- Null payload: Empty POST request (valid for some APIs)
- File uploads: Use CURLFile objects in array payload
Parameters
- $url : string
-
Target URL to send data to (must include protocol)
- $payload : mixed|null = null
-
Request body data (string, array, or null)
- $config : HttpClientConfig|null = null
-
Optional request configuration
Tags
Return values
HttpResult —Complete response object with server response and metadata
postJson()
Execute HTTP POST request with automatic JSON encoding and headers
public
static postJson(string $url, array<string|int, mixed> $payload[, HttpClientConfig|null $config = null ]) : HttpResult
Convenience method that automatically JSON-encodes array payload and sets appropriate Content-Type header for JSON API communication. Equivalent to calling post() with json_encode() and manual header configuration.
Automatic Configuration
- Payload automatically JSON-encoded using json_encode()
- Content-Type header automatically set to 'application/json'
- HttpClientConfig created automatically if not provided
- All other POST functionality available (auth, timeouts, etc.)
Parameters
- $url : string
-
Target API endpoint for JSON data submission
- $payload : array<string|int, mixed>
-
Associative array to be JSON-encoded as request body
- $config : HttpClientConfig|null = null
-
Optional configuration (auto-created if null)
Tags
Return values
HttpResult —Complete response object with API response and metadata
put()
Execute HTTP PUT request to update or create resource at specific endpoint
public
static put(string $url[, mixed|null $payload = null ][, HttpClientConfig|null $config = null ]) : HttpResult
Performs idempotent PUT request to update entire resource or create new resource at specified URL. Supports same payload formats as POST method but with different semantic meaning per REST conventions.
REST Semantics
- Update Existing: Replace entire resource with provided data
- Create New: Create resource at specific URL if it doesn't exist
- Idempotent: Multiple identical requests should have same result
- Complete Replacement: Partial updates typically use PATCH method
Parameters
- $url : string
-
Target resource URL for update/creation
- $payload : mixed|null = null
-
Complete resource data (string, array, or null)
- $config : HttpClientConfig|null = null
-
Optional request configuration
Tags
Return values
HttpResult —Complete response with server confirmation and metadata
request()
Core HTTP request implementation using cURL
private
static request(string $method, string $url[, mixed|null $payload = null ][, HttpClientConfig|null $config = null ]) : HttpResult
Internal method that executes HTTP requests with cURL, handles authentication, captures responses, and manages performance tracking via HttpResult objects.
Parameters
- $method : string
-
HTTP method (GET, POST, PUT, DELETE, etc.)
- $url : string
-
Target URL
- $payload : mixed|null = null
-
Request body data or null
- $config : HttpClientConfig|null = null
-
Request configuration or null for defaults
Tags
Return values
HttpResult —Complete response object with metadata