How can PHP scripts efficiently check the availability of domains listed in a database to minimize server workload?
To efficiently check the availability of domains listed in a database and minimize server workload, you can use a multi-curl approach in PHP. This involves sending multiple HTTP requests simultaneously to check the availability of domains in parallel, reducing the overall execution time.
<?php
// Function to check domain availability using cURL
function checkDomainAvailability($domain)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $domain);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode == 200) {
return true; // Domain is available
} else {
return false; // Domain is not available
}
}
// Array of domains to check
$domains = array("https://example1.com", "https://example2.com", "https://example3.com");
// Initialize multi-curl
$mh = curl_multi_init();
// Loop through each domain and add it to multi-curl
foreach ($domains as $domain) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $domain);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_multi_add_handle($mh, $ch);
}
// Execute multi-curl requests
$running = null;
do {
curl_multi_exec($mh, $running);
} while ($running > 0);
// Check the availability of each domain
foreach ($domains as $domain) {
if (checkDomainAvailability($domain)) {
echo $domain . " is available." . PHP_EOL;
} else {
echo $domain . " is not available." . PHP_EOL;
}
}
// Close multi-curl
curl_multi_close($mh);
?>