Pr0no
Pr0no

Reputation: 4099

How to catch error when get_headers() tries to resolve unresolvable host?

Consider the following:

$url = 'http://psyng.com/u/9716602b';
$headers = get_headers($url, 1);
print_r($headers);

Since the domain psyng.com is unresolvable, this code results in:

Warning: get_headers(): php_network_getaddresses: getaddrinfo failed: 
No such host is known

And then the script stops running. Is there a way to keep the rest of the script running - in other words: to catch the error, and move forward with resolving the next URL? So something like:

$url = 'http://psyng.com/u/9716602b';
$headers = get_headers($url, 1);
if ($headers == 'No such host is known') {
  // nevermind, just move on to the next URL in the list...
}
else {
  // resolve header stuff...
}

Upvotes: 2

Views: 4053

Answers (2)

mjsa
mjsa

Reputation: 4399

The function get_headers returns a boolean result; the purpose of print_r is to return boolean in a human readable format.

<?php
$url = 'http://psyng.com/u/9716602b';
$headers = get_headers($url, 1);
if ($headers === FALSE) { //Test for a boolean result.
  // nevermind, just move on to the next URL in the list...
}
else {
  // resolve header stuff...
}
?>

Upvotes: 0

Michael Mior
Michael Mior

Reputation: 28752

The script shouldn't stop running as the message produced is just a warning. I tested this script myself and that's the behaviour I see. You can see in the documentation that get_headers() will return FALSE on failure so your condition should actually be

if ($headers === FALSE) {
    // nevermind, just move on to the next URL in the list...

Upvotes: 3

Related Questions