Facebook PHP API throwing array reference exception - php

I am re-asking this question. The original occurrence went away after retrying the post, but on Dec 9, it has happened again, with greater frequency. I now have over 140 requests backed up that are failing with this same error inside the Facebook PHP API, and retrying the posts still fails. Dumping out the value of $rawResponse header shows:
{"
Just a left brace followed by a double quote, so it looks like the original function response is probably some JSON. Not sure what function made the original call, looking into that if I can make this happen in my DEV environment.
So, I just got back from vacation, and find that the Facebook PHP API was throwing this error:
Undefined offset: 1 in /home/httpd/idxv3/lib/Facebook-v5/Http/GraphRawResponse.php on line 108
The line is in this function:
public function
setHttpResponseCodeFromHeader($rawResponseHeader)
{
preg_match('|HTTP/\d\.\d\s+(\d+)\s+.*|', $rawResponseHeader, $match);
$this->httpResponseCode = (int)$match[1]; // <---- HERE
}
Other than the dangerous programming, why is this suddenly happening?

Ok, I believe that I have determined the problem. I recreated my Facebook API post inside the debugger, and determined that there is a block on the particular page I am posting to - but Facebook is returning a block of JSON code, which the API can't seem to handle. So, my question is moot - the API isn't written to handle the return values it might be getting from Facebook. Lovely.

Related

POST 500 (Internal Server Error) - Ajax & laravel 4

Sorry if my explanation is bad. Anyways, I have this todo list made by using laravel 4 sometime last year. Been working great for the last few months and I stopped playing around with it. Somehow I was playing around with it just yesterday and now it's giving me this POST 500 (internal Server ERROR). The Ajax call was working perfectly before. I had this error with chrome last night and today I tried using firefox, somehow it worked but then few minutes after, I am getting the same error in firefox too. By the way, a few ajax call is used here. Adding an item uses ajax to post what's added with a done button (this ajax is working perfectly). When the done button is clicked it should become a delete button and this is the ajax that's giving me the error. I went to the app.php to turn the debug => true
This error message is shown
{"error":{"type":"ErrorException","message":"Creating default object from empty value","file":"\/home2
\/.........\/TodoController.php","line":174}}
In my line 174 I have $query->done = 1;
that line is inside of this function
public function doubleDQuery($table, $id, $todoText, $done, $action){
$query = $table::where('id', '=', $id)->where('todoText', '=', $todoText)
->where('done', '=', $done)->first();
if($action == 'done'){
$query->done = 1;
$query->touch();
$query->save();
}
if($action == 'delete'){
$query->delete();
}
}
if I commented out the $query->done = 1, it gives me an error to the next line
{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"Call to a member
function touch() on a non-object","file":"\/home2\......\/TodoController
.php","line":175}}
if I commented the above line up, it gives me the error of none-object to save().
No modification is done for the past months and it was working for like a minute in firefox as mentioned above. I just have no idea where I should start looking for an answer, can someone give me a hand where I should start looking?
I have read that since 500 is internal server error it might be the server instead of my codes but it's weird that the other ajax call in the same application works just this is giving me the headaches.
That just means that $query is not what you think it is.
It seems to be null which means that there is no entry in the database matching your where clause. Although you expect it, respectively require it to be an object and also an instance of your model class for this code to work, without throwing an exception.
So you can either check for null manually and do whatever you wan't like:
if($query === null) {
//No matching row found
}
Or use firstOrFail() instead of first() which will actually already throw an exception with a 404 status code which may be what you want because you probably want to handle it properly on the client side.

get last bitcoin price bitstamp

My goal is fairly simple, this is a PHP file and I included it into my header because I want to display the last bitcoin price using bitstamp.net not any other bitcoin exchange prices.
<?php
function getprice($url){
$decode = file_get_contents($url);
return json_decode($decode, true);
}
$btcUSD = getPrice('https://www.bitstamp.net/api/ticker/ '); //bitstamp
$btcPrice = $btcUSD["last"];
$tempround = round($btcPrice, 2);
$btc_Display = "$".$tempround;
?>
Well, this seems to work, but some times upon refreshing the page I get an error.
Warning: file_get_contents(https://www.bitstamp.net/api/ticker/ ):
failed to open stream: HTTP request failed! HTTP/1.1 400 BAD_REQUEST
in C:\xampp\htdocs\hidden\btcprice.php on line 3
The error doesn't happen often its very random in timing, but what does it mean and how can I prevent it?
It took me a while to get the error because I don't know what is causing it. I'm curious how to prevent it, am I leaving something out? I used a guide to learn how to do this that got the last bitcoin price from btc-e, but I don't want to use btc-e. I have to use bitstamp last price.
Also no JavaScript is allowed (or should I say I'm trying to avoid JavaScript for this little project) and I don't understand PHP OOP stuff, so please no examples in that.
Your code is working for me. The w3.org defines 400 as follows:
The request could not be understood by the server due to malformed
syntax. The client SHOULD NOT repeat the request without
modifications.
However, that can happen when you use a Web-Api. Espacially Api's from Bitcoin-exchanges can be pretty unstable and answer with errors from time to time, according to my own experience. How RobotMind already mentioned, you should put a
try
{
}
catch
{
}
around the getPricefunction.
Another option is to use Curl. This way you can easily access the Status-Code and react accordingly if an error should happen.

cURL returns half json string in most cases

First edit (more details):
I used Modify Headers plugin in Firefox and visited the page (http://api.wunderlist.com/me/tasks), this showed the full and correct json string that I need. It never fails (25+ tests)
I tried using file_get_contents, but also file_get_contents cuts the response down. At various points.
cURL does the same, cuts down the response json at various points. Looks "at random"
Original post:
I'm breaking my head on a strange issue here. I've created a PHP Wrapper for Wunderlist2 (http://www.wunderlist.com) which can be found here: https://github.com/PENDOnl/Wunderlist2-PHP-Wrapper
It worked perfectly until I was notified by a user that the class stopped working all of a sudden. Since I created a free service (http://wcal.me) to provide a calendar feed for Wunderlist users, I decided to take a look at that script since that's the most easy way for me to debug the script.
Login in to Wunderlist and fetching the authtoken works, also all other functions in the class seem to work find (getting 'me', 'me/lists', etc.) However, in case of the getTasks function ('me/tasks') the response that I get is not complete, it simply stops in the middle of a json string. Therefor the json_decode function returns NULL and thus no tasks will be available in the calender feed/method response.
I also noticed that it's pretty random, because in some cases (<10%) it works like it should, but after another refresh the output is cut in half again. Also, the exact location of the 'cut' is different per refresh.
Is there anyone that can identify what the problem is? I tried to see if there is a way to wait untill a complete download of the file before it is returned, but it would be strange if that wasn't the default behaviour of cURL. I also tried to increase the timeout time, but since it returns a value I guess it doesn't timeout either.
All code can be foundin the Github repo, so far this is the only part I've changed to debug:
// get / put / delete requests should have HTTP Code 200 OK
// only exception is the login method, which returns HTTP Code 200 OK
if($httpCode == 200 && (strtolower($method) != 'post' || $action == '/login'))
{
$return = json_decode($output, true);
if($_SERVER['REMOTE_ADDR'] == MY_IP) {
if( is_null($return) ) {
echo "<b>Output of json_decode is null:</b><br><br>";
echo $output;
} else {
echo "<b>Output of json_decode os not null:</b><br><br>";
echo $output;
}
}
return $return;
}
The full response should look like something similar to this:
[{"assignee_id":null,"completed_at":null,"completed_by_id":null,"created_at":"2013-11-10T13:16:54Z"},{"assignee_id":null,"completed_at":null,"completed_by_id":null,"created_at":"2013-11-10T13:16:54Z"}]
But instead in most cases it's:
[{"assignee_id":null,"completed_at":null,"completed_by_id":null,"created_at":"2013-11-10T13:16:54Z"},{"assignee
Of course, this is a minified response, there is more information in the response available and there are many more items in the array.
For testing purposes, if you authenticate with the class, what result does browsing to http://api.wunderlist.com/me/tasks yield?
Also I'm sure you've already fixed but in base.class.php, $action is being checked for empty values twice instead of $action & $method.
Problem was with Wunderlist, just waiting for their fix :)

No element found FF - Error visible in firebug

I'm creating a global high score table. The JavaScript sends the username and score to the PHP through some AJAX functions and POST. The PHP script then takes the variable, and compares the score values to the file on the server. It then puts the new score where it should go on the score table, and rewrites the file.
I had it working last night, but now, when I call the function, it displays my code instead, and firebug gives the error, "No element found". I'm not sure what I did between then and now, but I just can't figure this one out.
This is my first time using PHP and AJAX, so I'm not sure where or what the error is.
Any help would be appreciated!
The exact error:
Timestamp: 4/13/2013 1:59:18 PM
Error: no element found
Source File: file:///C:/wamp/www/ajax.php
Line: 84, Column: 3
Source Code:
?>
If I cannot help you solve this issue, I will delete this answer, but I wanted to post it like this so you can better read my suggestions.
Start by changing your HandleResponse function to this:
function HandleResponse(response)
{
console.log(response);
document.getElementById('ResponseDiv').innerHTML = response;
}
and post the result that appears above the error, in firebug.
What we are doing here is adding a way for us to see if any data was actually returned from the AJAX request. A call to console.log tells the browser to print the given argument to the console (in your case, firebug).
UPDATE 1
In your comments, you stated that nothing displayed when you logged the value of response. This means that you received nothing back from the server (in terms of data, at least).
My next suggestion is that you change the call to MakeRequest to the following:
<input type='button' id="test" onclick='MakeRequest("*");' value='Global Highscore Table'/>
Like before, leave the console.log line in the HandleResponse method, and post the result that appears above the error in firebug.
Here, we are setting your MakeRequest to make a request that passes a wild-card query parameter. At the time of this suggestion, I did not realize that the requested file expected two arguments, nor that passing a wild-card would error the script. However, this was still a good thing to do, as we found a new error, which tells us that the request is being received.
UPDATE 2
Now, cut and paste everything from your "ajax.php" file to your notepad or another, similar application. Then, set the following to be the only content of the "ajax.php" file:
<?php echo "Request received and response sent"; ?>
Again, post the result of the console.log.
Here, we are taking a step back from fixing the complex code, and we are going back to the basics. All we want to do, here, is verify that we can both send the request and receive a response.
If "Request received and response sent" is successfully returned as the response of the request, then we know that the error lies in ajax.php, and not in the request. If it is not, we know that there is a problem with the request (be it a server issue or the request, itself). If the latter is the case, there could still be a problem with ajax.php, but we must first fix the request.
UPDATE 3 (final solution)
Issue was found to be due to not correctly running on the local server.

Baffled: PHP Fatal error: Exception thrown without a stack frame in Unknown on line 0?

I have found that one common reason for the error is an exception being thrown from within an exception handler. I'm quite sure this doesn't happen in the application I'm trying to debug... But I've put all the initialization processing lines at the top of index.php in a try/catch.*
It can apparently also happen because some things cannot be serialized to be stored in a session. At most this application stores arrays into the session (quite a bit), but I'm confident that it doesn't store anything too out of the ordinary in it.
Someone commented that it happened to them because their primary key needed to be CHAR(32) instead of INT(11). The PK's in this app are all INTs.
Other suggestions are that it could be a problem with PHP 5.3.3 fixed in 5.3.6, full disk, and a need to typecast a SimpleXML value. We do happen to be running PHP 5.3.3, but upgrading would have to be a last resort in this case. It hasn't always been doing this.
UPDATE/NOTE: I actually can't reproduce the error myself, only see it happening in the logs, see below paragraph for where I believe the error is happening...
* From the error logs, it seems likely that at least one place it is happening is index.php. I am deducing this only because it is indicated in some entries by a referring URL. The try/catch code is currently only around the "top" initialization portion of the script, below that is mostly the HTML output. There is some PHP code in the output (pretty straightforward stuff though), so I may need to test that. Here is the catch part, which is not producing any output in the logs:
} catch (Exception $e) {
error_log(get_class($e)." thrown. Message: ".$e->getMessage(). " in " . $e->getFile() . " on line ".$e->getLine());
error_log('Exception trace stack: ' . print_r($e->getTrace(),1));
}
Would really appreciate any tips on this!
EDIT: PHP is running as an Apache module (Server API: Apache 2.0 Handler). I don't think there are any PHP accelerators in use, but it could just be that I don't know how to tell. None of the ones listed on Wikipedia are in phpinfo().
As far as I can tell the MPM is prefork. This is the first I'd ever looked into the MPM:
# ./httpd -l
Compiled in modules:
core.c
prefork.c
http_core.c
mod_so.c
The problem
In short you have a exception thrown somewhere, you have no idea where and up until now you could not reproduce the error: It only happens for some people, but not for you. You know that it happens for other people, because you see that in the error logs.
Reproduce the problem
Since you have already eliminated the common reasons you will need to reproduce the error. If you know which parameter will cause the error it should be easy to locate the error.
Most likely it is enough if you know all the POST/GET parameters.
If you can't reproduce with just these, you need to know additional request headers. Such as user agent, accept-encoding,...
If you still can't reproduce, then it becomes very difficult: The error may depend on a state (a session), the current time, the source ip address or the like.
The custom log method
Let's start simple: To get all parameters you can write in the very beginning of the affected php file something like:
file_put_contents("/path/to/some/custom_error_log", date()."\n".print_r(get_defined_vars(), true), FILE_APPEND | LOCK_EX);
Don't forget that the custom_error_log file must be writable to your php application. Then, when the error occurs in the error log, find the corresponding lines in your custom_error_log file. Hopefully there are not to many requests per second so that you can still identify the request. Maybe some additional parameters in the error log like source ip can help you identify the request (if your error log shows that).
From that data, reconstruct a request with the same POST/GET parameters.
The tcpdump method
The next option that is very simple as well, but requires you to have root-access on your target machine is to install tcpflow. Then create a folder, cd into that folder and simply execute (as root) tcpflow "port 80". The option (port 80) is a pcap filter expression. To see all you can do with that, see man pcap-filter. There is a lot what these filter expressions can do.
Now tcpflow will record all tcp connections on port 80, reconstruct the full data exchange by combining the packages belonging to one connection and dump this data to a file, creating two new files per connection, one for incoming data and one for outgoing data. Now find the files for a connection that caused an error, again based on the timestamp in your error log and by the last modified timestamp of the files. Then you get the full http request headers. You can now reconstruct the HTTP request completely, including setting the same accept-encoding, user-agent, etc. You can even pipe the request directly into netcat, replaying the exact request. Beware though that some arguments like a sessionid might be in your way. If php discovers that a session is expired you may just get a redirect to a login or something else that is unexpected. You may need to exchange things like the session id.
Mocking more things
If none of this helps and you can't reproduce the error on your machine, then you can try to mock everything that is hard to mock. For example the source ip adress. This might make some stunts necessary, but it is possible: You can connect to your server using ssh with the "-w" option, creating a tunnel interface. Then assign the offending ip adress to your own machine and set routes (route add host ) rules to use the tunnel for the specific ip. If you can cable the two computers directly together then you can even do it without the tunnel.
Don't foget to mock the session which should be esiest. You can read all session variables using the method with print_r(get_defined_vars()). Then you need to create a session with exactly the same variables.
Ask the user
Another option would be actually ask the user what he was doing. Maybe you can follow the same steps as he and can reproduce.
If none of this helps
If none of that helps... well... Then it gets seriously difficult. The IP-thing is already highly unlikely. It could be a GEO-IP library that causes the error on IPs from a specific region, but these are all rather unlikely things. If none of the above helped you to reproduce the problem, then you probably just did not find the correct request in all the data generated by the custom_log_file-call / tcpflow. Try to increase your chances by getting a more accurate timestamp. You can use microtime() in php as a replacement for date(). Check your webserver, if you can get something more accurate than seconds in your error log. Write your own implementation of "tail", that gives you a more accurate timestamp,... Reduce the load on the system, so that you don't have to choose from that much data (try another time of day, load of users to different servers,...)
circle the problem once you can reproduce
Now once you can reproduce it should be a walk in the park to find the actual cause. You can find the parameter that causes the error by trial and error or by comparing it to other requests that caused an error, too, looking for similarities. And then you can see what this parameter does, which libraries access it, etc. You can disable every component one by one that uses the parameter until you can't reproduce anymore. Then you got your component and can dive into the problem deeper.
Tell us what you found. I am curious ;-).
I had such an error, too. Found out that I returned a sql object in my session class (that was used by the session_handler) instead of returning nothing or at least not the sql object. First look into your _write and _read methods, if you too return some incorrect stuff.
Notice: ... Unknown on line 0 - How to find correct line, it's NOT "line 0"
I realize this question has already been answered, but I'll add this since it may help someone:
I managed to (unintentionally) produce errors without a stack frame from a function which used its own error handler to maintain control of execution while calling a potentially "dangerous" function, like this:
// Assume the function my_error_handler() has been defined to convert any
// PHP Errors, Warnings, or Notices into Exceptions.
function foo() {
// maintain control if danger() crashes outright:
set_error_handler('my_error_handler');
try {
// Do some stuff.
$r = danger();
} catch (Exception $e) {
$r = 'Bad Stuff, Man!';
}
restore error_handler();
return $r;
}
The "untraceable failure" would happen at the end of the program execution if the logic in "Do some stuff" returned from foo() directly, bypassing the call to restore_error_handler(). What I took away from the experience is this:
PHP maintains a stack of error handlers which gets deeper/taller with each call to set_error_handler().
Bad Stuff can happen if you push error handlers onto the stack and don't clean up after yourself before the program exits "normally".
This was a tough bug to isolate - I basically narrowed the problem down to the above function and then stared at it until my eyes bled.
So how would I have tracked this down, knowing what I know now? Since I don't know of any way to inspect the PHP error handler "stack" directly, I'm thinking it might make sense to use a Singleton object to encapsulate all set/restore operations for PHP error handlers. At least then it would be possible to inspect the state of the Singleton before exiting the program normally, and if "dangling" error handlers are detected to generate a sensible failure/warning message before PHP freaks out.
Instead of wrapping code in a try/catch block, what happens when you register an exception handler? Clearly your try/catch block is not catching the exception, thus resulting in the errors logged to Apache. By registering a handler, you can be sure any uncaught exception is handled.
Also, if you're using namespaces in your application, make sure you write \Exception in your catch block (or include the Exception class via a use statement).
This may be a little late but one issue I discovered when moving a site from a local to a remote server. I was using Concrete5 cms had developed my site locally(windows 8 in xampp) and then uploaded to a remote server running Cent 0S
Windows mysql by default is case insensitive and created a lower case database. Once this was uploaded to the remote server I received the "Exception thrown without a stack frame in Unknown on line 0?"
I then corrected the database tables case and my site started working again.
For us, this error was due to inadvertently serializing SimpleXML objects.
If you are using SimpleXML objects with 5.3.3, make sure you are are casting the node values to whatever you need (e.g. string) if you are serializing the values in the session.
Before:
$token = $response->Token->Value;
/* token saved in session, results in line 0 error */
After:
$token = (string) $response->Token->Value;
/* token saved in session, no error */
I had completely the same error. A very spacial case: if you connect an unnamed function (closure) hook to an object instance's hook point. After that you try to serialize this object.
I had the same error after filling the Illuminate Eloquent model's Fillable property incorrectly. Note the last 3 elements of the array, one is missing a coma.
protected $fillable = [
'budget',
'routestatus' ,
'userroutenumber'
'totalmovingseconds',
'totalidleseconds'
];
I had the same error, it appeared upgrading server from centos 5 to centos 6 and downgrading PHP from 5.4 to 5.3. Actual issue was PHP apc, not configured properly. Check your APC. I was using Symfony2, so you might find some help at Symfony Unable to allocate memory for pool
one simple way to produce this error is an old server with register_globals = On. then you only need two lines of code:
<?php
$_SESSION["my_var"] = "string";
$my_var = new MyClass(); //could be any class, i guess
?>
as soon as you reload this page once, you'll get the Exception thrown without a stack frame in Unknown on line 0 - error. seems like there is a conflict between the instance of the class and the (session) variable.
at least this is how i got this annoying error which is so hard to debug.
This problem occurred for me when I changed the namespace on a few Symfony bundles. Deleting the files in the the symfony cache directory fixed the issue.
Likely you have a corrupt/inconsistent table in the database. Try dumping the database. If you get a error that's the time. Repair that table and the issue should go away.
It is for this reason why clean install works. The clean install is just that clean.
mysqlcheck should work but if it does not show and issue still do above.

Categories