tags:

views:

314

answers:

3

Hello,

How do I check if an URL exists and not 404 in PHP

Thanks Jean

+6  A: 

Here:

$file = 'http://www.domain.com/somefile.jpg';
$file_headers = @get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
    $exists = false;
}
else {
    $exists = true;
}

From here: http://www.php.net/manual/en/function.file-exists.php#75064

...and right below the above post, there's a curl solution:

function url_exists($url) {
    if (!$fp = curl_init($url)) return false;
    return true;
}
karim79
@karim79: I'm afraid the CURL-way won't work this way. Check this out: http://stackoverflow.com/questions/981954/how-can-one-check-to-see-if-a-remote-file-exists-using-php/982045#982045
Török Gábor
A: 

$f1 = 'http://www.sample.com/file.jpg'; $file_headers = @get_headers($f1); if($file_headers[0] == 'HTTP/1.1 404 Not Found') { $exists = false; } else { $exists = true; }

Rinu
A: 

Careful, get_headers("http://www.domain.com/somefile.jpg") can be very slow (1 minute)

Ka