I wrote a PHP code like this
$site="http://www.google.com"; $content = file_get_content($site); echo $content;
But when I remove "http://" from $site
I get the following warning:
Warning: file_get_contents(www.google.com) [function.file-get-contents]: failed to open stream:
I tried try
and catch
but it didn't work.
The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string. It will use memory mapping techniques, if this is supported by the server, to enhance performance.
file — Reads entire file contents into an array of lines. file_get_contents — Reads entire file contents into a string.
This function is similar to file(), except that file_get_contents() returns the file in a string, starting at the specified offset up to length bytes. On failure, file_get_contents() will return false . file_get_contents() is the preferred way to read the contents of a file into a string.
Short answer: No. file_get_contents is basically just a shortcut for fopen, fread, fclose etc - so I imagine opening a file pointer and freading it isn't cached.
Step 1: check the return code: if($content === FALSE) { // handle error here... }
Step 2: suppress the warning by putting an error control operator (i.e. @
) in front of the call to file_get_contents(): $content = @file_get_contents($site);
You can also set your error handler as an anonymous function that calls an Exception and use a try / catch on that exception.
set_error_handler( function ($severity, $message, $file, $line) { throw new ErrorException($message, $severity, $severity, $file, $line); } ); try { file_get_contents('www.google.com'); } catch (Exception $e) { echo $e->getMessage(); } restore_error_handler();
Seems like a lot of code to catch one little error, but if you're using exceptions throughout your app, you would only need to do this once, way at the top (in an included config file, for instance), and it will convert all your errors to Exceptions throughout.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With