I am using the following PHP:
$xml = simplexml_load_file($request_url) or die("url not loading");
I use:
$status = $xml->Response->Status->code;
To check the status of the response. 200 bening everything is ok, carry on.
However if I get a 403 access denied error, how do I catch this in PHP so I can return a user friendly warning?
To retrieve the HTTP response code from a call to simplexml_load_file(), the only way I know is to use PHP's little known $http_response_header. This variable is automagically created as an array containing each response header separately, everytime you make a HTTP request through the HTTP wrapper. In other words, everytime you use simplexml_load_file() or file_get_contents() with a URL that starts with "http://"
You can inspect its content with a print_r() such as
$xml = #simplexml_load_file($request_url);
print_r($http_response_header);
In your case, though, you might want to retrieve the XML separately with file_get_contents() then, test whether you got a 4xx response, then if not, pass the body to simplexml_load_string(). For instance:
$response = #file_get_contents($request_url);
if (preg_match('#^HTTP/... 4..#', $http_response_header[0]))
{
// received a 4xx response
}
$xml = simplexml_load_string($response);
You'll have to use something like the cURL module or the HTTP module to fetch the file, then use the functionality provided by them to detect an HTTP error, then pass the string from them into simplexml_load_string.
Related
I develop at php Laravel.
I receiving GuzzleHttp response from Mailgun as Object and can't to get from it the status.
the Object is:
O:8:"stdClass":2:{s:18:"http_response_body";O:8:"stdClass":2:{s:6:"member";O:8:"stdClass":4:{s:7:"address";s:24:"test_of_json-4#zapara.fr";s:4:"name";s:10:"not filled";s:10:"subscribed";b:1;s:4:"vars";O:8:"stdClass":0:{}}s:7:"message";s:36:"Mailing list member has been created";}s:18:"http_response_code";i:200;}
I need just last data pair:
"http_response_code";i:200;
to get it into variable, like:
$http_response_code = 200;
or even just its value.
To get string as I cited above I use
$result_ser = serialize($result);
but yet can't to extract value of variable.
Also I tried this:
$this->resultString .= \GuzzleHttp\json_decode($result_ser, true);
and get error.
Please, explain me , How to get/extract value I needed?
To take the response status code you can use the function getStatusCode :
$response = $client->request();
$statusCode = $response->getStatusCode();
while to take the body of response you can use :
$contents = $response->getBody()->getContents();
let's consider your request is something like
$response = $client->get("https://example.com");
if ( $object_res->getStatusCode() == 200 ) { // here you are checking your http status code
}
$object_res->getStatusCode() is the method to get http status code.
refer docs, there is simple example in this page.
I found that 'mailgun/mailgun' package uses its own HTTP client which also uses 'RestClient' and these classes are return stdObject.
In that Object there is property 'http_response_code' containing HTTP response code like 200, 400, 401 etc.
This property accessible by standard way $object->property and it's a solution of my query in this case.
For anybody who will read this question and answers I should to explain one thing that I not cleared in question.
I made request to the Mailgun API for subscribing member to mailing list. The API returns stdObject, not JSON or XML data.
But also there is one more strange thing - stdObject returned when request is successful only. If request fails you'll get just Exception thrown with message and without code. This forced me, if fail, to parse message body instead of get and resolve error code.
$responseObj->getStatusCode();
So I am trying to get some information from a JSON file. But for some reason there is no actual response with the information that I need.
This is the code im running.
$json_object = file_get_contents('http://steamcommunity.com/profiles/'.$steamID.'/inventory/json/730/2');
$json_decoded = json_decode($json_object);
echo $json_decoded->success;
I get the steamID from a cookie. But if you want to see how the JSON looks, then you can check out this link:
http://steamcommunity.com/profiles/76561198031313244/inventory/json/730/2
The problem is that the URL you are checking is redirected to another URL, file_get_contents() doesn't support following redirects AFAIK, so you should better use cURL
Check this answer https://stackoverflow.com/a/4324018/5658508
the problem is like the others tell you is in this link http://steamcommunity.com/profiles/76561198031313244/inventory/json/730/2
i just monitor the response, so when you visit the link you get a 302 Moved Temporarily http response to the new link which is http://steamcommunity.com/id/SANDISS/inventory/json/730/2
you can try to get contents using file_get_contents if you have the link not just a steam id, or use curl library
i'm connecting to a webservice using PHP and JSON. the connection is good but i want to add 2 error messages when (1) connection to the webservice is lost and (2) if webservice returns a http 500 error.
any ideas on how to do that?? i'm new to json so not sure how to do that...
this is how i connect and get data form the webservice
$url = "http://webservice.com/{$account}?loc={$loc}";
$content = file_get_contents($url);
$json = json_decode($content, true);
For error 1:
file_get_contents will return FALSE if what it is trying to load fails.
For error 2:
Depending on what your HTTP Error 500 outputs on the page, you can simply use file_get_contents and look for a certain string indicating the error using strpos and act accordingly.
Reference: http://php.net/manual/en/function.strpos.php
I'm using a file_get_contents to interact with an api for simple GET requests... however sometimes it throws headers signifying there's been an error. How can I get these headers and determine if there's a problem?
Php will set $http_response_header after file_get_contents which contains the response headers as an array of header lines/strings. Its not necessary to use curl if all you want is the headers responses (and probably shouldn't, some LAMP stacks still don't have cURL).
Doc on $http_response_header: http://php.net/manual/en/reserved.variables.httpresponseheader.php
Example:
file_get_contents('http://stacksocks.com');
foreach ($http_response_header as $header)
{
echo $header . "<br>\n";
}
Tips taken from post in comments:
1) The value changes with each request
made.
2) When used in methods/functions, the
current value must be passed to the
method/function. Using
$http_response_header directly in the
method/function without being assigned
a value by a function/method parameter
will result in the error message:
Notice: Undefined variable:
http_response_header
3) The array length and value
locations in the array may change
depending on the server being queried
and the response received. I'm not
sure if there are any 'absolute' value
positions in the array.
4) $http_response_header ONLY gets
populated using file_get_contents()
when using a URL and NOT a local file.
This is stated in the description when
it mentions the HTTP_wrapper.
Use curl instead of file_get_contents.
See: http://www.php.net/manual/en/curl.examples-basic.php
I imagine if your communicating with a REST Api then your actaully wanting the Http Status code returned. In which case you could do something like this:
<?php
$ch = curl_init("http://www.example.com/api/users/1");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) == 501) {
echo 'Ops it not implemented';
}
fclose($fp);
?>
file_get_contents('http://example.com');
var_dump($http_response_header);
I am using PHP with the Amazon Payments web service. I'm having problems with some of my requests. Amazon is returning an error as it should, however the way it goes about it is giving me problems.
Amazon returns XML data with a message about the error, but it also throws an HTTP 400 (or even 404 sometimes). This makes file_get_contents() throw an error right away and I have no way to get the content. I've tried using cURL also, but never got it to give me back a response.
I really need a way to get the XML returned regardless of HTTP status code. It has an important "message" element that gives me clues as to why my billing requests are failing.
Does anyone have a cURL example or otherwise that will allow me to do this? All my requests currently use file_get_contents() but I am not opposed to changing them. Everyone else seems to think cURL is the "right" way.
You have to define custom stream context (3rd argument of function file_get_contents) with ignore_errors option on.
As a follow-up to DoubleThink's post, here is a working example:
$url = 'http://whatever.com';
//Set stream options
$opts = array(
'http' => array('ignore_errors' => true)
);
//Create the stream context
$context = stream_context_create($opts);
//Open the file using the defined context
$file = file_get_contents($url, false, $context);