I’ve just set up a website with a new host and uploaded bits and bobs only to find that my script to get a particular users tweets had broken. I was being told that i had exceeded my limit of 150 calls to the twitter api.
At the time this may have made sense as i was testing everything and reloading the page a lot. However I’ve made only a couple of attempts today but all i ever get is the same error. I even rewrote my code so that it cached all the tweets i asked for for an hour, meaning at most 1 call an hour but its still not changing. Heres the code im using to get, cache and retrieve tweets;
function getUrl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
function getContent($file, $url, $hours = 1)
{
//vars
$CurrentTime = time();
$ExpireTime = $hours * 60 * 60;
$FileTime = filemtime($file);
if(file_exists($file) && ($CurrentTime - $ExpireTime < $FileTime))
{
//echo 'returning from cached file';
return json_decode(file_get_contents($file), true);
}
else
{
$content = getUrl($url);
$fh = fopen($file, 'w');
fwrite($fh, $content);
fclose($fh);
//echo 'retrieved fresh from '.$url.':: '.$content;
return json_decode($content, true);
}
}
$NumTweets = 3;
$AccountName = "TWITTERUSERNAME"; //this can be any username
$URL = "https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=".$AccountName."&count=".$NumTweets;
$XML = getContent('./lib/inc/tweets.txt', $URL);
I then use the following to define the tweets and time they were created, then print them out in a similar manor;
for($i = 0; $i < $NumTweets; $i++)
{
$Tweet['text'][$i] = formatTwitString($XML[$i]['text']);
$Tweet['time'][$i] = formatTwitTime($XML[$i]['created_at']);
}
The format functions are irrelevant, i know they work fine.
The thing is, if i manually enter the $URL var that gets generated in my browser, i can load the tweets without a problem, its only when loading it through the website that i get the error, i tried copying the content using this method and saving it to a file on another webserver and replacing the twitter $URL with the other servers url and that worked fine,
so i dont think theres anything wrong with my code, but somehow my calls to twitter are getting rinsed, could this be other websites on the same host(iPage.com) using up these calls to twitter somehow?
I’m a bit lost, please help,
Thanks.
There’s a chance your requests to Twitter are being made with the server’s primary shared IP, causing your rate limiting to be shared with other users on the server. You can work around this by authenticating to Twitter when making the API requests.
https://dev.twitter.com/docs/rate-limiting#rest
By authenticating, you get your own rate limit regardless of the IP address used.