0

I found a very nice class, WP_Http, in the WordPress core to grab external web page contents.

The problem is that it throws a PHP error when the url is not found, Fatal error: Cannot use object of type WP_Error as array.

$url = 'http://asklsahgioa.fdjeoiao.griawpo';   // non-existent url
$oHttp = new WP_Http;
$output = $oHttp->request($url);
print_r($output['body']);

So I'd like to make sure if the url exists prior to the class method. The following code works but it's slow and I can see the response takes for a second or so when the url is found. That means it doulbes the speed down if the url is fine.

$handle = @fopen($url,'r');
if($handle !== false)
   echo 'true';
else
   echo 'false';

I tried get_headers() as well; however, it also takes for a second when the url is found.

$siteHeader = @get_headers($url , 1);
if ($siteHeader > 1) 
    echo 'true';
else 
    echo 'false';

So, is there a better way of doing this? Maybe WordPress already has a function for it or extend the class to embed the error handling?

Teno
  • 2,582
  • 4
  • 35
  • 57

2 Answers2

3

How about checking to see if $output is a WP_Error returned by a failed request?

$output = $oHttp->request($url);

if ($output instanceof WP_Error) {
  // handle error
  echo 'something terrible has happened';
} else {
  print_r($output['body']);
}

(Note that the instanceof operator won't work in older versions of PHP)

rjz
  • 16,182
  • 3
  • 36
  • 35
  • 2
    I realized that I could simply use `wp_remote_get()` http://codex.wordpress.org/Function_API/wp_remote_get Thanks for the link. – Teno Sep 13 '12 at 02:20
1

This snippet is actually not the correct way to check whether the request has failed or not.

I am referring you to an answer I have posted on Stack Overflow, which will show you what's the best practice for this sort of task.

Community
  • 1
  • 1
Maor H.
  • 554
  • 5
  • 5
  • This is absolutely right. Your linked SO answer is the best solution, and should be checked as the best answer to this question – realtebo Oct 17 '16 at 08:06