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
- How can the use of PHP tags and correct syntax prevent errors when including XML declarations in PHP scripts?
- What are the advantages of using PHP tags correctly when writing PHP code for web development projects?
- Wie kann man verhindern, dass eine PHP-Datei mit iframes beim Betätigen der Zurücktaste des Browsers die Seite verlässt?