How can one check if a URL exists in PHP?
To check if a URL exists in PHP, you can use the `get_headers()` function to retrieve the headers of the URL. If the URL exists, the function will return an array of headers, including the HTTP status code. You can then check if the status code is within the range of 200 to 399 to determine if the URL exists.
function urlExists($url){
$headers = @get_headers($url);
if($headers && strpos($headers[0], '200') !== false){
return true;
} else {
return false;
}
}
$url = "https://www.example.com";
if(urlExists($url)){
echo "URL exists";
} else {
echo "URL does not exist";
}
Keywords
Related Questions
- What are the considerations for choosing a hosting provider that supports PHP functionalities like cron jobs for automated tasks?
- How can PHP developers ensure the security and efficiency of session management when using frames in web development?
- How can error reporting be enabled in PHP to help identify issues in the code?