tags:

views:

78

answers:

5

How do I check if a URI exists with PHP?

I guess it will return an error code and I can check it before I use file_get_contents, because if I use file_get_contents on a link that doesn't exist, it gives me an error.

+2  A: 

try the function array get_headers($url, [, int $format = 0 ]), it should return false on failure - otherwise, you can assume the uri exists, since the web server provided you with header info.

I hope the function uses an HTTP HEAD request as opposed to a GET, which should result in a lot less traffic than in the fopen solutions above.

Daren Thomas
+3  A: 

Try something like:

if ($_REQUEST[url] != "") {
    $result = 1;
    if (! ereg("^https?://",$_REQUEST[url])) {
        $status = "This demo requires a fully qualified http:// URL";
    } else {
        if (@fopen($_REQUEST[url],"r")) {
            $status = "This URL s readable";
        } else {
            $status = "This URL is not readable";
        }
    }
} else {
    $result = 0;
    $status = "no URL entered (yet)";
}

Then afterwards you can call this function using:

if ($result != 0) {
    print "Checking URL <b>".htmlspecialchars($_REQUEST[url])."</b><br />";
}
print "$status";
lugte098
ereg() is deprecated in PHP 5.3 and will be removed with PHP 6. you should use preg_match() instead.
Philippe Gerber
O, right. Thanks for the heads up!
lugte098
+4  A: 

You can send a CURL request to the uri/url. Depending on the protocol you can check the result. For HTTP you should check for the HTTP status code 404. Check the curl manual on php.net. In some cases you can use the file_exists() function.

<?php
$curl = curl_init('http://www.example.com/');
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_exec($curl);
$info = curl_getinfo($curl);
echo $info['http_code']; // gives 200
curl_close($curl);

$curl = curl_init('http://www.example.com/notfound');
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_exec($curl);
$info = curl_getinfo($curl);
echo $info['http_code']; // gives 404
curl_close($curl);
Progman
+2  A: 
try {
    $fp = @fsockopen($url, 80);
    if (false === $fp) throw new Exception('URI does not exist');
    fclose($fp); 
    // do stuff you want to do it the URI exists
} catch (Exception $e) {
    echo $e->getMessage();
}
Richard Knop
+1  A: 

checkdnsrr() does a DNS lookup. Might be of use.

chelmertz