PHP check if file exists by URL
This quick PHP snippet can be used to check if a specific URL exists. I use this in one of my projects for checking the existence of a robots.txt file on the site. Can be modified to check for files on any publicly accessible site.
$protocol = is_ssl() ? 'https://' : 'http://'; // uses WP function is_ssl()
$robots = $protocol . $_SERVER['SERVER_NAME'] .'/robots.txt';
$exists = false;
if (!$exists && in_array('curl', get_loaded_extensions())) {
$ch = curl_init($robots);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
$response = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($response === 200) $exists = true;
curl_close($ch);
}
if (!$exists && function_exists('get_headers')) {
$headers = @get_headers($robots);
if ($headers) {
if (strpos($headers[0], '404') !== false) {
$exists = true;
}
}
}
Here is how this works:
- Sets three variables:
$protocol
,$robots
, and$exists
- Check if PHP’s
curl
is available; if so, then use it to check for the specified URL ($robots
variable) - Check if
get_headers
is available; if so, then use it to check for the specified URL ($robots
variable)
So the end result of this script will be that the $exists
variable will return as true
if the specified file/URL exists. Otherwise $exists
remains false
.
Notes: If WordPress is not available, you’ll need to modify or remove the $protocol
variable accordingly. Also may want to change the $robots
variable throughout depending on usage. And lastly, make sure to specify the URL of whichever resource/file you want to check.