Check if URI exists?

How to check if a URI exists with PHP?

I assume that it will return an error code, and I can check it before using file_get_contents, because if I use file_get_contentsfor a link that does not exist, it gives me an error.

+3
source share
5 answers

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

I hope that the function uses the HTTP HEAD request, not GET, which should result in significantly less traffic than in the solutions described above fopen.

+2
source

CURL uri/url. . HTTP HTTP 404. php.net. file_exists().

<?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);
+4

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 you can call this function using:

if ($result != 0) {
    print "Checking URL <b>".htmlspecialchars($_REQUEST[url])."</b><br />";
}
print "$status";
+3
source
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();
}
+2
source

checkdnsrr()Performs a DNS lookup. May be helpful.

+1
source

Source: https://habr.com/ru/post/1736679/


All Articles