Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will file_get_contents fail gracefully?

I need file_get_contents to be fault tolerant, as in, if the $url fed to it returns a 404, to tell me about it before it echos out a warning. Can this be done?

like image 956
Mild Fuzz Avatar asked Nov 09 '10 08:11

Mild Fuzz


People also ask

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.

What is File_get_contents in laravel?

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.


2 Answers

Any function that uses the HTTP wrapper to access a remote file as if it were local will automatically generate a local variable named $http_response_header in the local scope. You can access that variable to find information about what happened in a call to fopen, file_get_contents ... on a remote file.

You can suppress the warning using @: @file_get_contents.

If you don't care about what the error was, you can use @file_get_contents and compare the result to false:

$content = @file_get_contents(url);
if ($content === false) { /* failure */ } else { /* success */ }
like image 71
Victor Nicollet Avatar answered Oct 04 '22 21:10

Victor Nicollet


You could do an additional (HEAD) request to find out first, for instance

$response = get_headers($url);
if($response[1] === 'HTTP/1.1 200 OK') {
    $content = file_get_contents($url);
}

Or you can tell file_get_contents to ignore any errors and force-fetch the result of the $url by modifying the stream context:

echo file_get_contents(
    'http://www.example.com/foo.html',
    FALSE,
    stream_context_create(array('http'=>array('ignore_errors' => TRUE)))
)
like image 21
Gordon Avatar answered Oct 04 '22 23:10

Gordon