json response errors check on php - php

true json url
$url = 'https://tr.api.pvp.net/api/lol/tr/v1.4/summoner/by-name/r2aper1tuar?api_key=RGAPI-2F65B634-F9C5-4DA7-A5E3-1D955D5D1E3B';
$content = file_get_contents($url);
$json = json_decode($content);
These codes work but if JSON url is not true. It will show error on index.php
How can i check these error.
not true json
if i use "not true JSON" , I take this error.
{
"status": {
"message": "Not Found",
"status_code": 404
}
}
Now how to check errors ?

Check the response:
if( property_exists ( $json , "status" ) )
{
$status_code = $json -> status -> status_code;
$message = $json -> status -> message;
// do something...
}

Related

Recaptcha Response PHP 500 Internal Server Error

I'm trying to check with Ajax a ReCaptcha V2 from Google. The problem is I keep getting error 500. This is my code.
$response = file_get_contents($url);
$responseKeys = json_decode($response, true);
$success = $responseKeys['success'];
if(!$success) return json_encode(['status' => 'CAPTCHA_ERROR']);
sendMail($request);
$url is fine I double checked and if I do this instead:
$response = file_get_contents($url);
$responseKeys = json_decode($response, true);
return $responseKeys;
And I console.log it in the browser, I get the right response:
{"success":true,"challenge_ts":"2017-10-05T03:30:18Z","hostname":"mysite.com"}

How to get value success and value true recaptcha and place to if condition?

this is the code,
$response=#file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
and this the result when I print_r($response);
{ "success": true, "challenge_ts": "2016-09-17T03:11:53Z", "hostname": "www.blabla.com" }
actually I want to make codition with if condition.
for example :
if ($response success == true)
how do that?
The Response you are getting is in JSON format so for that you have to decode to php array and after that you can use it, see below:
$response=#file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response, true);
if($data['success'] == true) {
// Here your code
}

json_decode() in PHP not showing true or false statements

I have a response coming back that is JSON encoded, but when I decode it I lose the true/false attributes after using $var = json_decode($response);.
Here’s an example:
{
"domain": "my.domain.com",
"created_at": "2014-11-15 00:26:53.74059",
"valid_mx": true
}
I’ve even tried:
$var = json_decode($response, true);
But it still seems to drop the true/false. How can I properly pull the true/false from the response? What am I missing?
Your problem is with print_r, not json_decode.
print_r does not show true / false for true / false. Instead, it shows 1 / (blank).
You can use var_dump($var); or var_export($var); instead which will show you the correct values.
This should work for you:
(With this you have the JSON string as an array)
<?php
$response = '{
"domain": "my.domain.com",
"created_at": "2014-11-15 00:26:53.74059",
"valid_mx": true
}';
$var = json_decode($response, true);
if($var["valid_mx"] === TRUE)
echo "true";
else
echo "false";
?>
Output:
yes
If you want an object just change this line:
$var = json_decode($response, true);
to this:
$var = json_decode($response);
And then you can access it with this line:
if($var->valid_mx === TRUE)
This works for me:
if(json_decode($response)->valid_max){
//your stuff
}

JSON element returning NULL

I am new to JSON and having a problem with checking at getting the error message when there is an error. My code works fine when the result is not an error, so I do somewhat understand what I am doing.
This is the error JSON that I am trying to parse:
{
"error": {
"message": "Unsupported get request.",
"type": "GraphMethodException",
"code": 100
}
}
Here is my code that fails:
$jsonurl = "http://graph.facebook.com/JubilationDanceMinistry";
//valid $jsonurl = "http://graph.facebook.com/WhitworthACM";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);
var_dump($json_output);
// This returns NULL
if (property_exists($json_output->error)) {
echo "<p>error: $json_output->error->{'message'} </p>";
} else {
echo "<p>no error :(</p>";
}
$facebook_id = $json_output->{'id'};
$facebook_name = $json_output->{'name'};
$facebook_link = $json_output->{'link'};
Because the url returns the 400 Bad Request.
By default, you can't use file_get_contents function to get the response content when the http status code is 400.
You need to set ignore_errors options to true.
$opts = array(
'http'=>array(
'ignore_errors' => true
)
);
$context = stream_context_create($opts);
$jsonurl = "http://graph.facebook.com/JubilationDanceMinistry";
$json = file_get_contents($jsonurl, false, $context);
var_dump($json);
You can't chain multiple ->'s with string interpolation.
You'll have resort to passing multiple arguments to echo or to string concatenation:
echo "<p>error: ", $json_output->error->{'message'}, " </p>";

Unable to parse JSON web service response with json_decode()

I'm struggling with parsing a web service response JSON in cases where the service returns an error.
Example JSON - success flow:
{
"Response": [{
"iconPath" : "/img/theme/destiny/icons/icon_psn.png",
"membershipType": 2,
"membershipId": "4611686018429261138",
"displayName": "Spuff_Monkey"
}],
"ErrorCode": 1,
"ThrottleSeconds": 0,
"ErrorStatus": "Success",
"Message": "Ok",
"MessageData":{}
}
Example JSON - error flow:
{
"ErrorCode": 7,
"ThrottleSeconds": 0,
"ErrorStatus": "ParameterParseFailure",
"Message": "Unable to parse your parameters. Please correct them, and try again.",
"MessageData": {}
}
Now my PHP:
function hitWebservice($endpoint) {
$curl = curl_init($endpoint);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
$json_response = curl_exec($curl);
if(curl_exec($curl) === false) {
echo "Curl error: " . curl_error($curl);
}
curl_close($curl);
$array_response = json_decode($json_response, true);
$function_response = array();
if (!isset($array_response['Response'])) {
$function_response = $array_response;
} else {
$function_response = $array_response['Response'];
}
return $function_response;
}
What I'm trying to achieve is when the JSON includes the "Response" block I put that in a new array and return only that detail from the function, where "Response" isn't present I want to return the full JSON as an array.
However at present, where there is no "Response" I get an empty array.
There's something wrong with my logic and I can't get past it in my tiny mind, so it's time to reach out for help!
Judging from the fact that Response is an array of objects in the JSON, I suspect that the error-flow response may also contain a Response-field, but with an empty array as value ([]). That would explain your current result.
Therefore, do not check for the existence of Response. It may just be an empty array. Instead, check for the ErrorCode, ErrorStatus or ErrorMessage (whichever you think is most suitable). For example:
if ($array_response['ErrorStatus'] != "Success") {
$function_response = $array_response;
} else {
if (!isset($array_response['Response'])) {
$function_response = null;
} else {
$function_response = $array_response['Response'];
}
}
In the Success-case, you want to check for existence of Response, so that if it does not exist (but it is expected), you can raise some error).
Another possible solution is to count the number of responses:
if (!isset($array_response['Response'])) {
$function_response = $array_response;
} else {
if (count($array_response['Response']) > 0) {
$function_response = $array_response['Response'];
} else {
$function_response = $array_response;
}
}
If you notice, both a good and a bad response contain an ErrorCode
You would be better designing your code to work from this field rather than test a field that may or may not exist.
So try this instead :-
$array_response = json_decode($json_response, true);
switch ( $array_response['ErrorCode'] ) {
case 1 :
do_errorCode_1_processing($array_response)
break;
case 2 :
do_errorCode_2_processing($array_response)
break;
// etc etc
}
isset () is not the right function for checking if the key in an array is present or not.
Use array_key_exists () instead.
http://php.net/manual/en/function.array-key-exists.php
so your code should look like this:
$array_response = json_decode($json_response, true);
$function_response = array();
if (array_key_exists('Response', $array_response)) {
$function_response = $array_response['Response'];
} else {
$function_response = $array_response;
}
return $function_response;
The above should do the trick.

Categories