file_get_contents error handeling?

Hi,

Im using file_get_contents to include a section from one of my other sites to another…see code below.


<?php
$latestVideos=file_get_contents("http://urltoinclude");

if ($latestVideos === false) {
      echo 'ERROR!';
   } else {
      echo $latestVideos;
   }
?>

Now, when this doesn’t work, I get the “ERROR!” printed, but I also get a “failed to open stream: HTTP request failed!” php-error thats rather ugly…

…how can I go around this and only get the message that it didnt work I want to display?

Hope you guys get what I mean! :slight_smile:

Thanks in advance!


if(!$fgc = file_get_contents(http://theurl))
{
   trigger_error('It\\'s all messed up');
   throw new Exception('This is nice error handling');
   exit('Could not continue);
   die('it is over');
}


that will throw the same error. You need to wrap that code in a conditional to check that the file exists first, e.g.

$url = 'http://www.example.com';
if (file_exists($url)) {
    // rest of code here
}

i rather think your wrong my friend, See as your making a level 2 or 3 system call with file_exists and just checking the results of file_get_contents is easy and quicker and according to the results you can ether throw an error or attempt to fix the error as what ever is needed to be done.

take this as some programming advice don’t try to guess what your errors or bugs could be rather catch the bug/errors and attempt to fix them.

Sorry, I didn’t understand a word of that.

The point is that if you only use file_get_contents() on a file/url that doesn’t exist, php throws a E_WARNING - to avoid that (and as good programming practice) test that the file exists first as I explained above.

Suppress the warning (the @ in the code) and check as done in your current implementation - it’s as simple as that.


if(FALSE !== ($content = @file_get_contents('http://...'))) {
      //... go on
}
else {
      die('Failed');
}

Good programming practice would be to use methods dedicated to remote resources (like cURL) and not to abuse file system methods.

Unfortunately aamonkey, kungknas is attempting to load remote data over HTTP and not a local file; so file_exists wouldn’t work.

As kungknas is addressing the warning raised by PHP, you could simply silence the warning with the @ operator - but it’s a slippery slope. :slight_smile:


<?php
if(false === ($data = @file_get_contents('http://example.org'))){
  #error
}

#use $data

yea anthothy example is perfectly correct

You are right Anthony - i typed it but it didn’t register that it was an external url :blush:

First, thanks for all the answers! …although they kinda made me a bit more confused here! :slight_smile:

So a better way to do it would be with cURL?

Something like this –> Download a URL’s Content Using PHP CURL?

yea that would work just fine.