Checking if the Twitter API is Up in PHP

Here’s a quick function that returns true if the Twitter API is up and responding, and false if otherwise:

function dieifnotup() {
   $tw = curl_init();
   curl_setopt($tw, CURLOPT_URL, "http://twitter.com/help/test.json");
   curl_setopt($tw, CURLOPT_RETURNTRANSFER, TRUE);
   curl_setopt($tw, CURLOPT_TIMEOUT, 5);
   $twi = curl_exec($tw);
   curl_close($tw);
   return (json_decode($twi) == "ok") ? true : false;
}

A practical use for this function would be to check if Twitter is up, and to call exit() if it’s not.


Update on August 16th, 2009: Include timeout to ensure the connection doesn’t hang. Thanks Eric!