Never trust file_get_contents without error catching
The function file_get_contents could get uncomfortable when it comes to error handling.The best (if you could call it that) way to handle errors from this function is to suppress the error
while calling the function, and checking if the result is false (of course one could always catch E_WARNING errors with a handler, but I don't like that).
This basically this piece of code:
1
2
3
4
5
<br />
$contents = file_get_contents($url);<br />
if ($contents === FALSE) {<br />
die('ERROR GETTING PAGE');<br />
}<br />
Lets you handle errors that could occur while trying to grab the file
There's however a big issue with that, it doesn't really tell you much about WHY
the error occurred.
A big issue here however, is that fact that
you don't really get the Reason of why the error occurred,
which is why Curl might be a better option (plus it's more robust & full of options).
In which case, you could write something like this:
1
2
3
4
5
6
7
8
$cur = curl_init('http://thisurlisnotworking.com/');
curl_setopt($cur, CURLOPT_RETURNTRANSFER, true);
$contents = curl_exec($cur);
if($contents === false)
echo 'Error: ' . curl_error($cur);
else
echo 'Curl Successful! Conent:'.$contents;</p>
<p>curl_close($cur);
This will display the error that has occurred, which is in my opinion
a pretty important thing to know.