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);
?>Current approach first; the original tutorial examples below are retained and cleaned up for continued learning and legacy maintenance.
<?php
$my_curl = curl_init();// cURL resource
// 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_exec($my_curl); //execute curl function now and display
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 provide practical use cases for verifying installation, installing cURL, and handling errors.
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.