Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I handle the warning of file_get_contents() function in PHP?

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.

like image 965
Waseem Avatar asked Nov 07 '08 15:11

Waseem


People also ask

What is the use of file_get_contents () function?

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.

What is the difference between file_get_contents () function and file () function?

file — Reads entire file contents into an array of lines. file_get_contents — Reads entire file contents into a string.

What does file_get_contents return?

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.

Does file_get_contents cache?

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.


2 Answers

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);

like image 138
Roel Avatar answered Sep 24 '22 08:09

Roel


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.

like image 30
enobrev Avatar answered Sep 26 '22 08:09

enobrev