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() handling error message
You need to check whether the call to file_get_contents
was 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();
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.
file_get_contents(): SSL operation failed with code 1, Failed to enable crypto
This was an enormously helpful link to find:
http://php.net/manual/en/migration56.openssl.php
An official document describing the changes made to open ssl in PHP 5.6
From here I learned of one more parameter I should have set to false: "verify_peer_name"=>false
Note: This has very significant security implications. Disabling verification potentially permits a MITM attacker to use an invalid certificate to eavesdrop on the requests. While it may be useful to do this in local development, other approaches should be used in production.
So my working code looks like this:
<?php
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
$response = file_get_contents("https://maps.co.weber.ut.us/arcgis/rest/services/SDE_composite_locator/GeocodeServer/findAddressCandidates?Street=&SingleLine=3042+N+1050+W&outFields=*&outSR=102100&searchExtent=&f=json", false, stream_context_create($arrContextOptions));
echo $response; ?>
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 not evaluating to false when file does not exist
file_get_contents()
generates an E_WARNING level error (failed to open stream) which is what you'll want to suppress as you're already handling it with your exception class.
You can suppress this warning by adding PHP's error control operator @
in front of file_get_contents()
, example:
<?php
$path = 'test.php';
if (@file_get_contents($path) === false) {
echo 'false';
die();
}
echo 'true';
?>
The above echoes false, without the @
operator it returns both the E_WARNING and the echoed false. It may be the case that the warning error is interfering with your throw function, but without seeing the code for that it's hard to say.
file_get_contents() how to fix error Failed to open stream, No such file
The URL is missing the protocol information. PHP thinks it is a filesystem path and tries to access the file at the specified location. However, the location doesn't actually exist in your filesystem and an error is thrown.
You'll need to add http
or https
at the beginning of the URL you're trying to get the contents from:
$json = json_decode(file_get_contents('http://...'));
As for the following error:
Unable to find the wrapper - did you forget to enable it when you configured PHP?
Your Apache installation probably wasn't compiled with SSL support. You could manually try to install OpenSSL and use it, or use cURL. I personally prefer cURL over file_get_contents()
. Here's a function you can use:
function curl_get_contents($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
Usage:
$url = 'https://...';
$json = json_decode(curl_get_contents($url));
file_get_contents() error
Your server must have the allow_url_fopen
property set to true. Being on a free webhost explains it, as it's usually disabled to prevent abuse. If you paid for your hosting, get in contact with your host so they can enable it for you.
If changing that setting is not an option, then have a look at the cURL library.
Related Topics
PHP Array, Are Array Indexes Case Sensitive
Call to Undefined Function Password_Hash()
How to Add a Condition Inside a PHP Array
What Do \R and \N Mean in PHP (And Other Languages)
Why Doesn't PHP Dom Include Slash on Self Closing Tags
MySQL Select a Piece of a String and Order by That Piece
Mysql_Fetch_Array Add All Rows
How to Count the Consecutive Duplicate Values in an Array
How Do We Implement Custom API-Only Authentication in Laravel
Convert Hex to Ascii Characters
Setting a Cookie in an Ajax Request
How to Render Content from String/Database with Twig
Jquery UI Saving Sortable List
Reply-To Address in PHP Contact Form