What are some best practices for handling HTTP headers and response codes in PHP when checking links?

When checking links in PHP, it is important to handle HTTP headers and response codes properly to ensure accurate results. One best practice is to use the PHP cURL library to make HTTP requests and retrieve the headers and response codes. By checking the response code, you can determine if the link is valid or if there is an error.

$url = 'https://example.com';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);

$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($httpCode == 200) {
    echo 'Link is valid';
} else {
    echo 'Link is invalid';
}

curl_close($ch);