Example
<?php
$url = 'https://api.example.com/status';
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 15,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_HTTPHEADER => ['Accept: application/json'],
]);
$response = curl_exec($ch);
$error = curl_error($ch);
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($response === false) {
error_log('cURL error: ' . $error);
throw new RuntimeException('The remote service could not be reached.');
}
if ($status < 200 || $status >= 300) {
throw new RuntimeException('Remote service returned HTTP ' . $status);
}
$result = json_decode($response, true);
Security and reliability
Use HTTPS, set connection and overall timeouts, and validate the response format. If the URL can be influenced by users, prevent server-side request forgery by enforcing a strict host allowlist and blocking private and internal network destinations.