Getting number of Twitter followers with plain PHP


Few days ago I wrote a tutorial for Twitter 1.1 API on how to get the number of Twitter followers in WordPress. Many people asked me how to do it in plain PHP, so I decided to write this small tutorial.

This is a rather simple implementation, but is complete with file caching the number of followers, so you can use this and be sure that you will not hit the Twitter API limit.

Feel free to use this in any way you see fit.

First, create a Cache.php file and copy this code in it:

* @desc Class that implements the Cache functionality
class Cache 
    const PATH_TO_CACHE = 'cache/';

    * @desc Function read retrieves value from cache
    * @param string $fileName - name of the cache file
    * @return bool/string
    * Usage: Cache::read('fileName.extension')
    function read($fileName) 
        $fileName = self::PATH_TO_CACHE . $fileName;
        if (file_exists($fileName)) {
            $handle = fopen($fileName, 'rb');
            $data = fread($handle, filesize($fileName));
            $data = unserialize($data);
            // checking if cache expired
            if (time() > $data[0]) {
                // it expired, delete the file
                return false;
            // cache is still valid, return the data
            return $data[1];
        } else {
            return false;
    * @desc Function for writing key => value to cache
    * @param string $fileName - name of the cache file (key)
    * @param mixed $variable - value
    * @param number $ttl - time to last in milliseconds
    * @return void
    * Usage: Cache::write('fileName.extension', value)
    function write($fileName, $variable, $ttl) 
        $fileName = self::PATH_TO_CACHE . $fileName;
        $handle = fopen($fileName, 'a');
        fwrite($handle, serialize(array(time() + $ttl, $variable)));
    * @desc Function for deleting cache file
    * @param string $fileName - name of the cache file (key)
    * @return void
    * Usage: Cache::delete('fileName.extension')
    function delete($fileName) 
        $fileName = self::PATH_TO_CACHE . $fileName;

This class will be used for caching purposes. As you noticed, inside the write method, I added a timestamp, so we can easily check if cache is still valid.

As an actual Twitter client, I will use an excellent PHP wrapper which is available on GitHub, I will not paste the code here as it is quite long. Create file TwitterAPIExchange.php and paste the contents of this file in:

Now, we have everything we need to make this work. This is our main function, so create getTwitterFollowers.php file and paste this in:

function getTwitterFollowers($screenName = 'codeforest')
    // this variables can be obtained in
    // to create the app, follow former tutorial on
    $settings = array(
        'oauth_access_token' => "YOUR_OAUTH_ACCESS_TOKEN",
        'oauth_access_token_secret' => "YOUR_OAUTH_ACCESS_TOKEN_SECRET",
        'consumer_key' => "YOUR_CONSUMER_KEY",
        'consumer_secret' => "YOUR_CONSUMER_SECRET"

    $cache = new Cache();
    // get follower count from cache
    $numberOfFollowers = $cache->read('cfTwitterFollowers.cache');
    // cache version does not exist or expired
    if (false === $numberOfFollowers) {
        // forming data for request
        $apiUrl = "";
        $requestMethod = 'GET';
        $getField = '?screen_name=' . $screenName;

        $twitter = new TwitterAPIExchange($settings);
        $response = $twitter->setGetfield($getField)
             ->buildOauth($apiUrl, $requestMethod)

        $followers = json_decode($response);
        $numberOfFollowers = $followers->followers_count;
        // cache for an hour
        $cache->write('cfTwitterFollowers.cache', $numberOfFollowers, 1*60*60);
    return $numberOfFollowers;

Now, where ever you need to show of your Twitter followers count, just add this code:

// set correct path!
// change screen name to yours
echo getTwitterFollowers('codeforest');

I hope I helped someone. Please feel free to share your thoughts or ideas in comment section below!

About the author

Zvonko Biškup

A passionate web developer with more than 13 years experience in PHP and other web related technology. My main interest is WordPress and new PHP frameworks.
Owner of Influendo Programming.
Enjoys exploring new stuff and possibilities, using new technologies and just having fun developing awesome stuff.

<span class="dsq-postid" data-dsqidentifier="1847">4 comments</span>

  • Hi It did work for me, but it showed me some errors with the cache files… ->

    Warning: fopen(cache/cfTwitterFollowers.cache) [function.fopen]: failed to open stream: No such file or directory in /data/sites/web/digital4be/www/website/twitter/Cache.php on line 47

    Warning: fwrite() expects parameter 1 to be resource, boolean given in /data/sites/web/digital4be/www/website/twitter/Cache.php on line 48

    Warning: fclose() expects parameter 1 to be resource, boolean given in /data/sites/web/digital4be/www/website/twitter/Cache.php on line 49

    For the moment I just turned off all error reports which does the trick. But if you can help me out with these errors feel free to leave a reply!

    Thank you for the script!

  • Hi Zvonko, thanks for the script.

    Can you help me with this error :
    Notice: Trying to get property of non-object in C:\xampplite\htdocs\rdtime\catalog\controller\common\footer.php on line 47

    line 47 : $numberOfFollowers = $followers->followers_count;


  • Hi winsen, did you get the solution? am also facing the same problem
    Notice: Trying to get property of non-object in C:wampwwwgetTwitterFollowers.php on line 32