HTTP requests with file_get_contents, getting the response code
http://php.net/manual/en/reserved.variables.httpresponseheader.php
$context = stream_context_create(['http' => ['ignore_errors' => true]]);
$result = file_get_contents("http://example.com", false, $context);
var_dump($http_response_header);
How to get php file_get_contents() error response content
So in the end everything posted here works as it should be. I should have made isolated test case before coming here. (But after debugging while it seems you have tried every option :P)
So I think the 'ignore_errors' => true, line was somehow overwritten or ignored but isolating it form the other code it worked like supposed and the value of $response if the content of the error message.
So in that case you need to do the error checking some other way than if($response === false). Very simple way could be if($http_response_header[0] != 'HTTP/1.1 200 OK') { handle error! }
Thanks for every ones input!
how to get HTTP status in variable with file_get_contents
Saty's answer is write, also i would like to suggest using curl, after curl_exec
, you can get all the information using curl_getinfo
Example from the same link:
<?php
// Create a curl handle
$ch = curl_init('http://www.example.com/');
// Execute
curl_exec($ch);
// Check if any error occurred
if(!curl_errno($ch))
{
$info = curl_getinfo($ch);
echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url'];
echo 'HTTP STATUS CODE: ' . $info['http_code'];
}
// Close handle
curl_close($ch);
?>
The result can be returned fetched from curl_exec using curl_setopt by settings CURLOPT_RETURNTRANSFER
to true
.
Example:
<?php
// Create a curl handle
$ch = curl_init('http://www.example.com/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute
$result = curl_exec($ch);
// Check if any error occurred
if(!curl_errno($ch))
{
$info = curl_getinfo($ch);
echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url'];
echo 'HTTP STATUS CODE: ' . $info['http_code'];
}
// Close handle
curl_close($ch);
// use $result
var_dump($result);
?>
file_get_contents and error codes
Try curl instead:
function get_data($url)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
if(!curl_errno($ch)){
return $data;
}else{
echo 'Curl error: ' . curl_error($ch);
}
curl_close($ch);
}
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);
Getting http status code from file_get_contents inside helper function
As Rick suggested in the comments you should use curl.
function get_json($zipcode) {
$api_key = KEY;
$url = 'https://example.com/request.json?api_key=' . $api_key . '&address=' . $zipcode;
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
$http_code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($http_code == 200) {
return json_decode($result, true);
} else {
return false;
}
}
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 ===
.
file_get_contents of php, doesn't provide proper error response of a https request
You can change this behavior by setting http.ignore_errors
to true.
<?php
$opts = [
"http" => [
'ignore_errors' => true
]
];
$context = stream_context_create($opts);
$hmaps_request = file_get_contents("https://geocode.search.hereapi.com/v1/geocode?apiKey={MY_API_KEY}&q=3891+Delwood+Drive%2C+Powell%2C+OH%2C+United+States", false, $context);
$json_details = json_decode($hmaps_request);
/* Output
object(stdClass)#1 (2) {
["error"]=>
string(12) "Unauthorized"
["error_description"]=>
string(33) "apiKey invalid. apiKey not found."
}
*/
var_dump($json_details);
PHP: How to GET request a page and get body and http error codes
You should try with curl
$ch = curl_init('https://httpstat.us/404');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// if you want to follow redirections
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// you may want to disable certificate verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode >= 400) {
// error
// but $response still contain the response
} else {
// everything is fine
}
curl_close($ch);
Related Topics
How to Remove Line Breaks (No Characters!) from the String
Codeigniter: How to Connect to Your Database Server Using the Provided Settings Error Message
Using an Array as Needles in Strpos
Check File Extension in Upload Form in PHP
How Unique Is the PHP Session Id
Print Numeric Values to Two Decimal Places
PHPexcel Runs Out of 256, 512 and Also 1024Mb of Ram
PHP: Regex to Ignore Escaped Quotes Within Quotes
How to Filter a Two Dimensional Array by Value
Encrypt and Decrypt Text With Rsa in PHP
PHP MySQL Google Chart Json - Complete Example
What Is the Point of Interfaces in PHP
How to Get Name of Calling Function/Method in PHP
How to Remove Accents and Turn Letters into "Plain" Ascii Characters