Good Error Handling with File_Get_Contents

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

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

file_get_contents good way to handle errors

Try cURL with curl_error instead of file_get_contents:

<?php
// Create a curl handle to a non-existing location
$ch = curl_init('http://404.php.net/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = '';
if( ($json = curl_exec($ch) ) === false)
{
echo 'Curl error: ' . curl_error($ch);
}
else
{
echo 'Operation completed without any errors';
}

// Close handle
curl_close($ch);
?>

file_get_contents() handling error message

You need to check whether the call to file_get_contentswas successful:

$t = microtime( TRUE );
@$content = file_get_contents( "http://www.example.org" );
if($content === FALSE) {
print "Site down"; // or other problem
} else {
$t = microtime( TRUE ) - $t;
print "It took $t seconds!";
}

The @ is there to suppress the warning. Also Note the ===.

Unable to catch PHP file_get_contents error using try catch block

try/catch doesn't work because a warning is not an exception.

You can try this code so you can catch warnings as well.

//set your own error handler before the call
set_error_handler(function ($err_severity, $err_msg, $err_file, $err_line, array $err_context)
{
throw new ErrorException( $err_msg, 0, $err_severity, $err_file, $err_line );
}, E_WARNING);

try {
$url = 'http://wxdex.ocm/pdd.jpg';
$file_content = file_get_contents($url);
} catch (Exception $e) {
echo 'Error Caught';
}

//restore the previous error handler
restore_error_handler();

Good error handling with file_get_contents

Here's an idea:

function fget_contents() {
$args = func_get_args();
// the @ can be removed if you lower error_reporting level
$contents = @call_user_func_array('file_get_contents', $args);

if ($contents === false) {
throw new Exception('Failed to open ' . $file);
} else {
return $contents;
}
}

Basically a wrapper to file_get_contents. It will throw an exception on failure.
To avoid having to override file_get_contents itself, you can

// change this
$dom->load(call_user_func_array('file_get_contents', $args), true);
// to
$dom->load(call_user_func_array('fget_contents', $args), true);

Now you can:

try {
$html3 = file_get_html(trim("$link"));
} catch (Exception $e) {
// handle error here
}

Error suppression (either by using @ or by lowering the error_reporting level is a valid solution. This can throw exceptions and you can use that to handle your errors. There are many reasons why file_get_contents might generate warnings, and PHP's manual itself recommends lowering error_reporting: See manual

How to catch the error of file_get_contents() in php

file_get_contents() returns FALSE on failure. You must check for that value with the === operator. If you wish to suppress the warning, you can use the @ operator in front of file_get_contents().

$contenido = @file_get_contents($url);
if (contenido === FALSE) {
$save=FALSE;
}

From the file_get_contents() docs:

Warning
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Global error handling of file_get_contents() PHP

you may set your custom error_handler before invoking file_get_contents and then use restore_error_handler() function right after file_get_contents. if there is multiple usage of file_get_contents in your code, you may wrap file_get_contents by some custom function.

How to handle 403 error in file_get_contents()?

Personally I'm suggesting you to use cURL instead of file_get_contents. file_get_contents is great for basic content oriented GET requests. But the header, HTTP request method, timeout, redirects, and other important things do not matter for it.

Nevertheless, to detect status code (403, 200, 500 etc.) you can use get_headers() call or $http_response_header auto-assigned variable.

$http_response_header is a predefined variable and it is updated on each file_get_contents call.

Following code may give you status code (403, 200 etc) directly.

preg_match( "#HTTP/[0-9\.]+\s+([0-9]+)#", $http_response_header[0], $match);
$statusCode = intval($match[1]);

For more information and content of variable please check official documentation

$http_response_header — HTTP response headers

get_headers — Fetches all the headers sent by the server in response to a HTTP request

(Better Alternative) cURL

Warning about $http_response_header, (from php.net)

Note that the HTTP wrapper has a hard
limit of 1024 characters for the header lines. Any HTTP header received that is longer than this will be ignored and won't appear in $http_response_header. The cURL extension doesn't have this limit.



Related Topics



Leave a reply



Submit