PHP Development

Build a Reusable PHP HTTP Client with cURL

Create a small HTTP client boundary that centralizes transport options, headers, timeouts and response handling for outbound integrations.

When several parts of an application call external services directly, each call tends to configure cURL differently. One may omit a timeout, another may follow redirects without restriction, and a third may log credentials. A reusable client creates one place to enforce transport policy while keeping provider-specific request and response mapping outside the low-level transport.

Separate transport from provider logic

A transport component should accept a method, URL, headers and optional body, then return a structured result containing status, headers and body. A provider adapter should know the external service's endpoint paths, authentication format and JSON schema. This separation makes it possible to test provider behavior with a fake transport and to change transport details without rewriting business logic.

Set safe defaults

Use a connection timeout and a total request timeout. Verify TLS certificates; do not disable peer or host verification to “fix” certificate errors. Restrict redirects or validate redirect destinations, especially when URLs can be influenced by users. Set an explicit Accept header and Content-Type when sending JSON. Avoid putting API secrets in query strings because URLs commonly appear in logs.

Minimal transport outline

$handle = curl_init($url);
curl_setopt_array($handle, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CONNECTTIMEOUT => 5,
    CURLOPT_TIMEOUT => 15,
    CURLOPT_FOLLOWLOCATION => false,
    CURLOPT_HTTPHEADER => $headers,
]);
$body = curl_exec($handle);
$status = (int) curl_getinfo($handle, CURLINFO_RESPONSE_CODE);
$error = curl_error($handle);
curl_close($handle);

Handle failures as distinct cases

A cURL transport error means no usable HTTP response was received. An HTTP 4xx or 5xx response is still a response and should be interpreted by the provider adapter. Keep response bodies bounded before logging or parsing. Never log Authorization headers or full payloads that may contain personal data.

Test the boundary

Inject or wrap the transport so tests can simulate timeouts, invalid JSON, 401 responses and provider outages. Verify that every request uses the configured timeout and TLS policy.

Further reading

Share this page Help other developers discover this resource.