I'm trying to use file_get_contents together with stream_context_create to make POST requests. My code so far:
$options = array('http' => array(
'method' => 'POST',
'content' => $data,
'header' =>
"Content-Type: text/plain\r\n" .
"Content-Length: " . strlen($data) . "\r\n"
));
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
It works fine, however, when an HTTP error occurs, it spits out a warning:
file_get_contents(...): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
and returns false. Is there a way to:
suppress a warning (I'm planning to throw my own exception in case of failure)
obtain the error information (at least, the response code) from the stream
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);
None of the answers (including the one accepted by OP) actually satisfy the two requirements:
suppress a warning (I'm planning to throw my own exception in case of failure)
obtain the error information (at least, the response code) from the stream
Here's my take:
function fetch(string $method, string $url, string $body, array $headers = []) {
$context = stream_context_create([
"http" => [
// http://docs.php.net/manual/en/context.http.php
"method" => $method,
"header" => implode("\r\n", $headers),
"content" => $body,
"ignore_errors" => true,
],
]);
$response = file_get_contents($url, false, $context);
/**
* #var array $http_response_header materializes out of thin air
*/
$status_line = $http_response_header[0];
preg_match('{HTTP\/\S*\s(\d{3})}', $status_line, $match);
$status = $match[1];
if ($status !== "200") {
throw new RuntimeException("unexpected response status: {$status_line}\n" . $response);
}
return $response;
}
This will throw for a non-200 response, but you can easily work from there, e.g. add a simple Response class and return new Response((int) $status, $response); if that fits your use-case better.
For example, to do a JSON POST to an API endpoint:
$response = fetch(
"POST",
"http://example.com/",
json_encode([
"foo" => "bar",
]),
[
"Content-Type: application/json",
"X-API-Key: 123456789",
]
);
Note the use of "ignore_errors" => true in the http context map - this will prevent the function from throwing errors for non-2xx status codes.
This is most likely the "right" amount of error-suppression for most use-cases - I do not recommend using the # error-suppression operator, as this will also suppress errors like simply passing the wrong arguments, which could inadvertently hide a bug in calling code.
Adding few more lines to the accepted response to get the http code
function getHttpCode($http_response_header)
{
if(is_array($http_response_header))
{
$parts=explode(' ',$http_response_header[0]);
if(count($parts)>1) //HTTP/1.0 <code> <text>
return intval($parts[1]); //Get code
}
return 0;
}
#file_get_contents("http://example.com");
$code=getHttpCode($http_response_header);
to hide the error output both comments are ok, ignore_errors = true or # (I prefer #)
To capture the error message when file_get_contents returns FALSE, write a function which uses ob_start and ob_get_contents to capture the error message that file_get_contents writes to stderr.
function fileGetContents( $fileName )
{
$errmsg = '' ;
ob_start( ) ;
$contents = file_get_contents( $fileName );
if ( $contents === FALSE )
{
$errmsg = ob_get_contents( ) ;
$errmsg .= "\nfile name:$fileName";
$contents = '' ;
}
ob_end_clean( ) ;
return (object)[ 'errmsg' => $errmsg, 'contents' => $contents ];
}
I go to this page with kind of a different issue, so posting my answer. My problem was that I was just trying to suppress the warning notification and display a customized warning message for the user, so this simple and obvious fix helped me:
// Suppress the warning messages
error_reporting(0);
$contents = file_get_contents($url);
if ($contents === false) {
print 'My warning message';
}
And if needed, turn back error reporting after that:
// Enable warning messages again
error_reporting(-1);
#file_get_contents and ignore_errors = true are not the same:
the first doesn't return anything;
the second suppresses error messages, but returns server response (e.g. 400 Bad request).
I use a function like this:
$result = file_get_contents(
$url_of_API,
false,
stream_context_create([
'http' => [
'content' => json_encode(['value1' => $value1, 'value2' => $value2]),
'header' => 'Authorization: Basic XXXXXXXXXXXXXXX',
'ignore_errors' => 1,
'method' => 'POST',
'timeout' => 10
]
])
);
return json_decode($result)->status;
It returns 200 (Ok) or 400 (Bad request).
It works perfectly and it's easier than cURL.
Related
I need to send a POST request to another file called global.php, for this I try this code below:
$url = 'global.php';
$data = array('stack' => 'overflow');
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result);
This is the global.php file that should process the request:
if(isset($_POST['stack'])){
echo 'exists';
}else{
echo 'error';
}
The problem is that instead of the command var_dump ($ result); show exists, it shows the PHP code? how can I solve this problem?
And why when I try to do the same thing using ajax it returns me the text exists and not PHP code?
You should use full url, to process php file through server.
$url = 'http://YOURURL.com/global.php';
AJAX call is made from browser, to absolute URL, thats why You are getting desired response.
I have the following class, it's using a web service to send a request and get a JSON response back.
When i try the same thing with Chrome's Postman extension, I get a nice little response back.
class RequestController {
function __construct() {
global $config;
$this->config = $config;
}
function send_request() {
$url = $this->config['GATEWAY']['url'] . 'getbyquery';
$json_data = '{"query":{"AllFields":true,"ConditionSetOperator":0,"ConditionSets":[],"Distinct":false,"Fields":["jay_alb","jay_levelms"],"Links":[],"Orders":[],"RecordType":"jay_lifeinsurance","Top":0}}';
$data = array($json_data);
$options = array(
'http' => array(
'header' => "Content-type: application/json\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
print "<pre>";
print_r($options);
print "</pre>";
$result = file_get_contents($url, false, $context);
$data = json_decode($result);
var_dump($data);
}
}
However when I'm using my class I get an error.
Warning: file_get_contents(http://crm-gateway.premier.com.au/GatewayService.svc/getbyquery) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 411 Length Required in C:\Program Files (x86)\Apache Software Foundation\Apache2.2\htdocs\crm\includes\classes\RequestController.php on line 32
Can you please point out what I'm doing wrong?
Thanks,
I am facing one issue while i am calling rest service using file_get_contents
its working fine when response is success but its giving blank result in case of failure or error response. while when I am checking it using rest client its giving me correct response for both case whether its success or failure.
can anyone please help? below is the source code which i have written.
<?php
$postdata = array(
'email' => $email,
'password' => $password
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => $headers = array(
'Accept: application/json',
'Content-Type: application/json'
)
//'content' => $postdata
)
);
$context = stream_context_create($opts);
//echo "<pre>"; print_r($context); exit;
$url = WS_URL . "issavvy-api/account/login?" . http_build_query($postdata);
$result = file_get_contents($url, false, $context);
echo "<pre>";
print_r(json_decode($result));
exit;
?>
If you wanna stick with file_get_contents use $http_response_header and parse it
You can use this
function httpStatusCode($headers){
$match = null;
$pattern = "!(?P<version>HTTP/\d+\.\d+) (?P<code>\d+) (?P<status>.*)!";
foreach($headers as $header){
if(preg_match($pattern, $header, $match)){
return $match['code'];
}
}
return null;
}
To check if request was successful run
$success = (200 == httpStatusCode($http_response_header));
https://eval.in/145906
If using file_get_contents() to connect to Facebook,
$response = file_get_contents("https://graph.facebook.com/...?access_token=***");
echo "Response: ($response)\n";
And the server returns a non-OK HTTP status, PHP gives a generic error response, and suppresses the response. The body returned is empty.
file_get_contents(...): failed to open stream: HTTP/1.0 400 Bad Request
Response: ()
But if we use cURL, we see that Facebook actually returns a useful response body:
{"error":{"message":"An active access...","type":"OAuthException","code":2500}}
How can I make file_get_contents() return the response body regardless of HTTP errors?
You have to use stream_context_create():
$ctx = stream_context_create(array(
'http' => array (
'ignore_errors' => TRUE
)
));
file_get_contents($url, FALSE, $ctx);
You could ignore the errors file_get_contents throws
$opts = array(
'http'=>array(
'ignore_errors'=> true,
)
);
$context = stream_context_create($opts);
$file = file_get_contents('https://graph.facebook.com/...?access_token=***', false, $context);
var_dump($file);
I need to pass these headers into the $context variable, i tried using putting the values into an array and then passing it into stream_context_create() function but i get http warnings from the file_getcontents function
$prod_id = 4322;
$tnxRef = "RT45635276GHF76783AC";
$mackey = "ADECNH576748GH638NHJ7393MKDSFE73903673";
$agent = $_SERVER['HTTP_USER_AGENT'];
$hash = hash('SHA512', $prod_id.$txnRef.$mackey);
$headers = array(
'http'=>(
'method'=>'GET',
'header'=>'Content: type=application/json \r\n'.
'$agent \r\n'.
'$hash'
)
)
stream_context_create($headers)
$url_returns = file_get_contents("https://test_server.com/test_paydirect/api/v1/gettransaction.json?productid=$prod_id&transactionreference=$txnRef&amount=$amount", false, $context);
$json = json_decode($url_returns, true);
Error:
[function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request`
Thats the error i get, can somebody please help with a definitive example.
You have several errors in your code.
The server returns 400 Bad Request, because your code would result in this incorrect HTTP request:
GET /test_paydirect/api/v1/gettransaction.json?productid=4322&transactionreference=RT45635276GHF76783AC&amount= HTTP/1.1
Host: test_server.com
Content: type=application/json
$agent
$hash
The errors are:
Variable expressions are not evaluated within single quotes
$amount is not set in your code example
The header is Content-Type: and not Content: type=
All headers (agent, hash) must have their corresponding name
Here is an example that should work:
$context = stream_context_create(array(
'http' => array(
'method' => 'GET',
'agent' => $agent,
'header' => "Content-Type: application/json\r\n"
. "X-Api-Signature: $hash"
)
)
);
Please note: X-Api-Signature is just an example - it depends on the API you are using how the API key header is named and how the hash is calculated. You should find this information in the Docs of your API!