1

I have a working function to get external website speed.

$t = microtime( TRUE );
file_get_contents( "http://www.example.org" );
$t = microtime( TRUE ) - $t;
print "It took $t seconds!";

However, if the external url is down, it prints this;

Warning: file_get_contents(http://www.example.org): failed to open stream: HTTP request failed! 
HTTP/1.0 500 Internal Server Error in /home/china/public_html/dene.php on line 47
It took 14.4556088448 seconds!

What is the corerct way, to print "Site down", instead of getting that error ?

user198989
  • 4,574
  • 19
  • 66
  • 95
  • 1
    Try cURL with curl_error instead of file_get_contents because file_get_contents do not throw an exception in error, instead it returns false, so you can check if the returned value is false Check here Answer given by @Andrey Volk http://stackoverflow.com/questions/16130818/file-get-contents-good-way-to-handle-errors#answer-16130898 – CY5 Aug 02 '15 at 15:19
  • in php 7.0 file_get_contents fail throws an exception – Daniel Krom Aug 02 '15 at 15:20

1 Answers1

3

You need to check whether the call to file_get_contentswas successful:

$t = microtime( TRUE );
@$content = file_get_contents( "http://www.example.org" );
if($content === FALSE) {
    print "Site down"; // or other problem
} else {
    $t = microtime( TRUE ) - $t;
    print "It took $t seconds!";
}

The @ is there to suppress the warning. Also Note the ===.

Bahram Ardalan
  • 280
  • 3
  • 11
CaringDev
  • 8,391
  • 1
  • 24
  • 43