BeTwittered, PHP and file_get_contents
January 20, 2008 – 9:28 amI spent a bit of time this morning adding to my error handling in BeTwittered. Around 8am there was a bit of a service issue at, I believe, the Twitter server end, but I had no way to confirm it. I was, as my own customer, just getting my own “OOPS, something went wrong” please stand by sort of message. The problem is that I used the PHP file_get_contents() function, which does not return HTTP error codes, and when using Twitters HTTP API, that’s key for error handling. To make a long story short: I discovered that, although the function does not return the HTTP status codes, that status DOES get stored in the global variable $http_response_header. Are you geeky enough to want to see how I captured this info? Then read on…
Here is the code, directly from my BeTwittered gadget, that requests the users time-line from the Twitter servers. The expected, happy, useful response is stored in $twitter_XML_raw, and I work with that to display it nicely elsewhere in the app. The key to catching the HTTP status codes is in the next line, using ‘list’ and ‘explode.’ The logic in how I will respond to the user is in the ’switch’ statement below. If you are interested in re-using this, you should be able to glean what you need from this. Feel free to leave a question in the comments if you like, though.
if(($twitter_XML_raw=file_get_contents($timeline))==false){
// Retrieve HTTP status code
list($version,$status_code,$msg) = explode(' ',$http_response_header[0], 3);
// Check the HTTP Status code
switch($status_code) {
case 200:
$error_status="200: Success";
break;
case 401:
$error_status="401: Login failure. Try logging out and back in. Password are ONLY used when posting.";
break;
case 400:
$error_status="400: Invalid request. You may have exceeded your rate limit.";
break;
case 404:
$error_status="404: Not found. This shouldn't happen. Please let me know what happened using the feedback link above.";
break;
case 500:
$error_status="500: Twitter servers replied with an error. Hopefully they'll be OK soon!";
break;
case 502:
$error_status="502: Twitter servers may be down or being upgraded. Hopefully they'll be OK soon!";
break;
case 503:
$error_status="503: Twitter service unavailable. Hopefully they'll be OK soon!";
break;
default:
$error_status="Undocumented error: " . $status_code;
break;
}