What is the best way to check if a given website URL exists using PHP?
One way to check if a given website URL exists in PHP is by using the `get_headers()` function, which sends a HEAD request to the URL and returns the response headers. We can then check if the response code is in the 200 range to determine if the URL exists.
function urlExists($url) {
$headers = @get_headers($url);
if($headers && strpos($headers[0], '200')) {
return true;
} else {
return false;
}
}
// Example usage
$url = 'https://www.example.com';
if(urlExists($url)) {
echo 'URL exists';
} else {
echo 'URL does not exist';
}
Keywords
Related Questions
- How can the "Cannot modify header information - headers already sent" error be resolved in PHP?
- What information can be obtained by running the phpinfo() script in PHP?
- In what situations would it be appropriate to request an API from website operators for accessing user data instead of using cURL in PHP?