Use cURL with explicit timeouts, return-transfer mode, and an error check. In PHP 8+, cURL handles are objects, so focus on request options and response/error handling rather than older resource-specific assumptions.
<?php
$ch = curl_init('https://example.com/');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 10,
CURLOPT_FOLLOWLOCATION => false,
]);
$response = curl_exec($ch);
if ($response === false) {
throw new RuntimeException(curl_error($ch));
}
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
echo "HTTP status: $status";
curl_close($ch);
?>The examples below build on this pattern and show common cURL request types.
<?php
$my_curl = curl_init(); // cURL handle
// WE will add options to our curl
curl_setopt($my_curl, CURLOPT_URL, "https://www.google.com/");
curl_setopt($my_curl, CURLOPT_HEADER, 0);
curl_setopt($my_curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($my_curl, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($my_curl, CURLOPT_TIMEOUT, 10);
$response = curl_exec($my_curl);
if ($response === false) {
throw new RuntimeException(curl_error($my_curl));
}
echo $response;
curl_close($my_curl); // close the curl connection
?>
if (function_exists('curl_version')) {
echo "cURL is installed.";
} else {
echo "cURL is not installed.";
}
sudo apt-get install php-curl
sudo service apache2 restart
$ch = curl_init('https://example.com');
if (!$ch) {
die('cURL not available!');
}
These examples cover extension checks, a typical Linux installation command, and basic request error handling. Keep TLS certificate verification enabled; fix the CA/certificate configuration instead of disabling verification.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.