on Tutorials

Getting number of Twitter followers with plain PHP

4 comments
twitter-bird-with-pc
Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on RedditShare on StumbleUpon

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
                @unlink($fileName);
                return false;
            }
            fclose($handle);
            // 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)));
        fclose($handle);
    }
     
    /**
    * @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;
        @unlink($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: https://github.com/J7mbo/twitter-api-php/blob/master/TwitterAPIExchange.php

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')
{
    require_once('Cache.php');
    require_once('TwitterAPIExchange.php');
    // this variables can be obtained in http://dev.twitter.com/apps
    // to create the app, follow former tutorial on http://www.codeforest.net/get-twitter-follower-count
    $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 = "https://api.twitter.com/1.1/users/show.json";
        $requestMethod = 'GET';
        $getField = '?screen_name=' . $screenName;

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

        $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!
require_once(getTwitterFollowers.php);
// 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!

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on RedditShare on StumbleUpon



4 Responses to “Getting number of Twitter followers with plain PHP”