What is the best practice for checking the existence of external pages in a link database using PHP?
When working with a link database in PHP, it's important to check the existence of external pages to ensure the links are valid and not broken. One way to do this is by sending a HTTP request to the URL and checking the response code. If the response code is in the 2xx range, it indicates that the page exists.
$url = 'https://example.com';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch);
$response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($response_code >= 200 && $response_code < 300) {
echo 'Page exists';
} else {
echo 'Page does not exist';
}
curl_close($ch);
Keywords
Related Questions
- How can nested arrays be properly accessed and displayed when parsing HTML in PHP?
- What best practice should be followed when determining whether to use the forum ID or forum link for the generated link?
- What are some ways to handle fatal errors in PHP, such as using functions like mysql_error() or try-catch blocks?