Search code examples
phpfile-get-contents

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?


Solution

  • 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 */ }