简体   繁体   中英

How to handle get_headers() function if URL doesn't exist

While usign the function get_headers() for example, If i wrote

get_headers("www.websitedoesntexist.com");

i get the following error

Warning: get_headers(): php_network_getaddresses: getaddrinfo failed: No such host is known Warning: get_headers(www.websitedoesntexist.com): failed to open stream: php_network_getaddresses: getaddrinfo failed: No such host is known

I want to know how to handle these problems, Something like

if (isset(get_headers("www.websitedoesntexist.com"))) {
    echo "URL Exists";
}

From the PHP manual :

Returns an indexed or associative array with the headers, or FALSE on failure.

Which means you can test against FALSE .

Read more : http://php.net/manual/en/function.get-headers.php

Edit

If you want just to check if the URL exists or not, instead of supressing the errors I suggest you use curl, a simple function like this can do the job :

function url_exists($url) {
    if (!$fp = curl_init($url)) {
        return false;
    } 
    return true;
}

Suppress errors on the get_headers() function. Assign get_headers to a variable. Then check the Boolean value of that variable.

 $file_headers = @get_headers("www.websitedoesntexist.com");
 if(!$file_headers) {
     $exists = false;
 }
 else {
     $exists = true;
 }

Edit:

Based on the comments, for a better, long-term solution using curl see https://stackoverflow.com/a/36743670/4374801

if you want to check the url exist or not in php, simply code this.testing purpose

$array = get_headers('url');
$string = $array[0];
    if (strpos($string, "200")) {
    echo "thats cool dude";
} else {
    echo "Bad request";
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM