PHP APIs

Making HTTP Requests in PHP with cURL

Learn how to send HTTP requests with PHP cURL, inspect response codes, handle errors, and decode JSON responses.

Making HTTP Requests in PHP with cURL

PHP cURL allows an application to communicate with remote HTTP services. It is commonly used to call REST APIs, retrieve resources, and send data to other systems.

Send a GET Request

Initialize a cURL handle, configure the URL and options, execute the request, and close the handle.

$ch = curl_init("https://api.example.com/status");

curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 15,
    CURLOPT_CONNECTTIMEOUT => 5,
    CURLOPT_FOLLOWLOCATION => false,
]);

$response = curl_exec($ch);

if ($response === false) {
    $error = curl_error($ch);
    curl_close($ch);
    throw new RuntimeException("HTTP request failed.");
}

$statusCode = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);

The example uses a placeholder API host. Replace it with a trusted service endpoint.

Decode a JSON Response

Check the HTTP status code before treating a response as successful. Then decode JSON with exception handling.

try {
    $data = json_decode($response, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $exception) {
    throw new RuntimeException("The API returned invalid JSON.");
}

A successful HTTP response does not guarantee that the returned data has the structure your application expects. Validate it before use.

Send a POST Request

For JSON APIs, encode the payload and set the appropriate content type.

$payload = json_encode(
    ["name" => "Example"],
    JSON_THROW_ON_ERROR
);

curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $payload,
    CURLOPT_HTTPHEADER => ["Content-Type: application/json"],
]);

In real code, create and configure the handle in one complete request flow, and include authentication headers only as required by the API provider.

Reliability and Security

Set connection and total timeouts, verify TLS certificates, handle non-2xx status codes, and avoid logging authorization tokens. Do not disable SSL verification to work around certificate errors.

Conclusion

cURL provides detailed control over HTTP requests in PHP. Timeouts, TLS verification, status-code checks, and response validation are important parts of reliable API integration.

Share this page Help other developers discover this resource.