"Use of undefined constant success - assumed 'success'" error parsing json response - php

im using google recaptcha and the way of my validation is through ajax, everything is working, I got a response
{
success: "false/true"
}
but i got an error saying "Use of undefined constant success - assumed 'success" on line 30, any ideas, help, suggestions, recommendations?
this is my code on the controller (the one i use in communicating the google recaptcha API)
$captcha=$request->input('g-recaptcha-response');
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=mysitekey&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
if($response.success == false) //this is the line 30
{
return 'You are spammer ! Get the out';
}else{
return 'Thanks for posting comment.';
}
this is the line 30 "$response.success == false"

You missed a couple of steps.
First you need to json_decode the response you get from the API
$responseData = json_decode($response);
Next you need to properly address the "success" element from which I assume will be an array, but you will verify this with a var_dump().
var_dump($responseData);
If you get an array then the if clause will look like this:
if ($responseData["success"]==false)
On the other hand if you get an object in the responseData, the `if clause will look like this
if ($responseData->success==false)
The dot notation is for javascript, in php the dot is a concatentation operator.

Related

datatable authentication for server side scripting

I am using jQuerydatables and server side scripting with php and mysql. I have modified the script found here:
https://legacy.datatables.net/examples/data_sources/server_side.html
and I have included an if-else which is wrapped around the entire script.
The goal is to only allow results to be returned if the user posted a valid token from my db.
So I have that bit set up. But I am unsure how to handle the error message to the user.
Right now, when a user passes in an invalid token, my website (using datatables) throws up the error invalid JSON response.
I assume this because it is expecting iTotalRecords etc in the JSON returned.
I am wondering if anyone knows how to achieve this. I haven't been able to find any examples.
Algorithm:
if (postedToken exists in db){
return datatables JSON
}
else{
return json in such a way that I can provide an alert to the user that their session has expired
}
and datatable initialisation:
"sAjaxSource": "mydatatablescript.php?token=<?php echo $token;?>
EDIT:
I was returning a valid JSON but I was missing a few parameters which must be required i.e. 'iTotalRecords' => 0, 'iTotalDisplayRecords' => 0, 'aaData' => [], 'sEcho' => 0.
Now I am not getting the error message described in the question. I see there is a "fnDrawCallback" parameter I can include in the datatable initialisation. I suspect here I can check my message param and alert if necessary but I just don't know how to access the JSON from within that function?
As you have seen already, you need to return valid json in any case if your client-side is expecting that.
You could do that using for example something like:
if (postedToken exists in db){
return datatables JSON
}
else{
return json_encode(array('success': false, 'message': 'session has expired'));
}
You should probably add these same keys / parameters when the call is successful as well so that you can easily check in your javascript function what the result of the operation is.

json_decode - issues with api

I am trying to find the game someone is playing on twitch by using the api. I have setup the json_decode and it shows all of the content from the api. However whenever I try to print_r the game I get an error.
The error:
Notice: Undefined property: stdClass::$game in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\projects\Portfolio -- Website\twitchstreaminfo\streaminfo.php on line31
PHP code:
$streamer = $_POST['username'];
$apiurl = "https://api.twitch.tv/kraken/streams/" . $streamer;
$apicontent = file_get_contents($apiurl);
$streamerinfo = json_decode($apicontent);
print_r($streamerinfo->game);
Try just doing the following first and verify the result:
print_r( $streamerinfo );
From what I can see with the API, the following should work:
print_r( $streamerinfo->stream->game );
Your error is saying that the propery of "$game" does not exist on the object "$streamerinfo". As suggested above, try priting the "$streamerinfo" to varify that it is valid. Another thing you can do to prevent this is to add the following :
if (isset($streamerinfo->game) {
print_r($streamerinfo->game);
}
That code will prevent this error, but not fix the problem. I suggest this as a final solution to help you solve the problem
if (isset($streamerinfo->game) {
print_r($streamerinfo->game);
} else {
print_r($streamerinfo);
}
This will keep your code from breaking in the way that it is now. But, it will also print "$streamerinfo" if it fails. This way you can see why it failed.

json_decode giving error in php for webservice call

I am consuming a webservice in PHP , below is code sample
> if ( $datas=file_get_contents($url) ) return json_decode($datas);
> return Array('error' => "Can't open url");
I return the the value of above function call to js page. but I dont get the value of webservice call in js but always get error value. However if I open the $url in browser I get below data (valid json) :
{"d":[ [ 5.305,428 ] ] }
Due to framework restriction i can use only json_decode() to return values back to my js page.
I also tried json_decode($datas,true); but still no help.
I also tried consuming same code in standalone php file :
I get this error : when I use json_decode($datas)
Catchable fatal error: Object of class stdClass could not be converted
to string in C:\xampp\htdocs\webservice-demo\clientRestTest.php on
line 32
and below error if I use json_decode($datas,true);
Notice: Array to string conversion in
C:\xampp\htdocs\webservice-demo\clientRestTest.php on line 32 Array
Please let me know how to resolve the issue .
Is there any special chars in $url? if there is, try urlencoding it first
file_get_contents(urlencode($url)); etc etc

How to display custom error instead of displaying simple html dom.php error

I'm working on a project which is simply scrapping the comments of youtube but the condition is not to use cURL. So i started using simple html dom.php.
I almost fought with many problems and now that are fixed. But i have a query that how to set an error for file_get_html() method.
For example:
I'm allowing user to enter the url of a youtube video, i have almost done a lot of validating of youtube URL, but still if someone will enter a wrong URL then the script will report this error:
*Warning: file_get_contents(http://www.youtube.com/watch?v=VR--anQO?????222cV--clS8): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in C:\xampp\htdocs\utube\simple_html_dom.php on line 39*
and i can't set error reporting to false as it's not allowed. So can you please say me how to display this error: Invalid URL instead of the error shown above. And yes please don't say about the youtube API as it's not allowed :(
The easiest way would be to use an #. Just use it like this:
if (#file_get_html(...)) {
//do whatever you want, if it suceeds
} else {
echo "Invalid URL";
}
You can find more information here.
As simple_html_dom is a class, that should be the reason why the # has no affect, as the class don't seem to regard it.
A thing worth a try: First try using file_get_contents, and only use simle_html_dom, if that works - like this:
if (#file_get_contents(...)) {
file_get_html(...);
//now anything else you want to do
} else {
echo "Invalid URL";
}

How to catch error in JSON response?

I'm getting the json data from the twitter using the wordpress function wp_remote_get as below:
$response = wp_remote_get('http://api.twitter.com/1/statuses/user_timeline.json?screen_name=twitter');
$json = json_decode($response['body']);
and it works fine. However, it totally creates the problem on my page if the twitter returns some error. In that case the content on my page does not load after that error part. So how can I catch the error and continue, only if there is no error.
For example if the twitter limit exceeds, it returns following response:
{"request":"\/1\/statuses\/user_timeline.json?screen_name=twitter","error":"Rate limit exceeded. Clients may not make more than 150 requests per hour."}
From the above responsive, how can i get the error.
I'm trying following, but it does not work (my page does not load at all)
if (!isset($json['error']){
//continue
}
It doesn't work because you are trying to access $json as an array, which it is not. It's an object, so use:
if (!isset($json->error){
//continue
}
Your page doesn't load because it's causing a fatal error, which in turn produces a 500 internal server error. If you check your error log you'll find:
Fatal error: Cannot use object of type stdClass as array in ....
You need to use json_decode to "transform" your "json string" in an object.
$j = json_decode($json);
echo $j->{'error'}
Here you will find everything what you need to know about json_decode: http://php.net/manual/en/function.json-decode.php

Categories