Jul 26, 2015

Get Social Media (Facebook, Twitter, YouTube, Google+) Followers Count Using PHP

Each social media provides their own widget to display followers count, but their user interfaces are different and so much javascript in the code. So I decided to get the count on server side using PHP, cache it and show it as I want. This post explains to get Twitter followers, Facebook fans, YouTube subscribers and Google+ page/profile followers count, to cache the results and generate HTML to display them.

social counter

Getting Started:

A global variable is used to have all Social media related configurations.

$social_counter_settings = array(		
			'twitter_user' => 'itechbrij',
			'consumer_key' => 'xxxxxxxxxxxxxxxxxxxxxxxxx',
			'consumer_secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
			'oauth_access_token' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
			'oauth_access_token_secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
			//Google API Key for Google related services
			'googleplus_id' => '+Techbrij',		
			'cache_file_name' => 'social-follower.txt'

You have to update all settings with your values.

First step is to create a Twitter application and get your consumer’s keys.

1. Visit https://dev.twitter.com/apps and login with your twitter credentials.

2. Create new application,enter the form fields and create your app.

3. On the application page, click the "Create my access token".

4. You will now have all kind of keys, use them in the $social_counter_settings variable.

To obtain a Free Google API Key:

1. Visit console.developers.google.com.

2. Create a new project.

3. Click APIs Under the APIs & auth menu.

4. Click "Google+ API" and click "Enable API"

5. Click "YouTube Data API" and click "Enable API"

6. Click Credentials under the APIs & auth menu.

7. Create a new browser key and leave the referrer box empty.

To get YouTube Channel ID,

Visit https://www.youtube.com/account_advanced. It provides both channel and user ids.

At this point, you have updated all values with yours.

Now create a variable which holds all count values.

$social_counter = array(
'twitter' => -1,
'facebook' => -1,
'googleplus' => -1,
'youtube' => -1		

By default, it has -1 value.

Read Also:

Add Social Slider (Facebook like box, twitter and Google+ Widgets) in Your Website

Facebook Fan Count:

Add the below function to get Facebook likes count

		* Facebook Like Count
		function facebook_follower_count() {		
			global $social_counter_settings;
			$settings = $social_counter_settings;
			$count = -1;				
			$fql  = "SELECT like_count FROM link_stat WHERE url = 'https://www.facebook.com/".$settings['facebook_id']."'"; 
			$fqlURL = "https://api.facebook.com/method/fql.query?format=json&query=" . urlencode($fql);
			// Facebook Response is in JSON
			$response = file_get_contents($fqlURL);
			$fb = json_decode($response);
			if ( isset( $fb[0]->like_count ) ) {				
						$count = intval( $fb[0]->like_count );					
			return $count ;

Twitter Follower Count:

As an actual Twitter client, I will use an excellent PHP wrapper Twitter-API-PHP available on GitHub, Create file TwitterAPIExchange.php and paste the contents from following file


Add the below function to get Twitter follower count

		* Twitter Follower Count
		//to get follower count
		function twitter_follower_count(){
			global $social_counter_settings;
			$count = -1;
			$settings = $social_counter_settings;
			  $apiUrl = "https://api.twitter.com/1.1/users/show.json";
				$requestMethod = 'GET';
				$getField = '?screen_name=' .  $settings['twitter_user']; 
				$twitter = new TwitterAPIExchange($settings);
				$response = $twitter->setGetfield($getField)->buildOauth($apiUrl, $requestMethod)->performRequest(); 
				$followers = json_decode($response);
				$count = $followers->followers_count;
			return $count ;

If you are getting following error:

Fatal error: Uncaught exception 'Exception' with message 'SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed' in TwitterAPIExchange.php:297

add below line at line 275 in performRequest method of TwitterAPIExchange.php to disable SSL verification.


and test it again.

YouTube Subscriber Count:

Add the below function to get YouTube subscriber count

		* YouTube Follower Count
		function youtube_follower_count() {		
			global $social_counter_settings;
			$settings = $social_counter_settings;
			$count = -1;				
			$youtubeUrl = "https://www.googleapis.com/youtube/v3/channels?part=statistics&id=".$settings['youtube_channel_id']."&key=".$settings['google_api_key'];			
			$response = file_get_contents($youtubeUrl);			
			$fb = json_decode($response);
			if ( isset( $fb->items[0])) {				
						$count = intval( $fb->items[0]->statistics -> subscriberCount);					
			return $count ;

Google+ Follower Count:

Add the below function to get Google+ follower count

		* Google+ Follower Count
		function googleplus_follower_count() {		
			global $social_counter_settings;
			$settings = $social_counter_settings;
			$count = -1;				
			$gUrl = "https://www.googleapis.com/plus/v1/people/".$settings['googleplus_id']."?key=".$settings['google_api_key'];			
			$response = file_get_contents($gUrl);			
			$fb = json_decode($response);
			if ( isset( $fb->circledByCount)) {				
						$count = intval($fb->circledByCount);					
			return $count ;


As we are using API to get count, these APIs are rate limited. So caching is used to avoid seeking new results every time a page is loaded. The new values are checked only once a day by default, but you can configure the interval.

		* Caching Function
		/* gets the contents of a file if it exists, otherwise grabs and caches */
function get_content($content,$forcewrite=false, $hours = 24) {
	global $social_counter_settings;
	$file = $social_counter_settings['cache_file_name'];
	$current_time = time(); $expire_time = $hours * 60 * 60; $file_time = filemtime($file);

	if(file_exists($file) && ($current_time - $expire_time < $file_time) && $forcewrite===false) {
		//echo 'returning from cached file';
		return json_decode(file_get_contents($file),true);
	else {			
		return $content;

Basically, we are saving and retrieving $social_counter variable in file in json format.

Display Counts:

Instead of calling individual method, taking advantage of naming convention in the below method.

function process_counts(){
    global $social_counter;
    $social_counter= get_content($social_counter);
    foreach ( $social_counter as $key => $value ) {
        if ($value < 0){
          $method = $key . '_follower_count';
          $social_counter[$key] = $method();
     if ($isdirty>0){
        //cache modified counts
        $social_counter= get_content($social_counter,true);
     return $social_counter;

It checks $social_counter values if it is -1 then call related method to get count. If any value is modified then it will be cached.

To display social count values in HTML format, use below function

function view_counts(){
    $counts = process_counts();
    $html = '<ul>';
    foreach ( $counts as $key => $value ) {	
	$html .= sprintf('<li>%s: %s followers</li>',$key, $value<0?0:$value);
    $html .= '</ul>';
    return $html;

and call the method in html where you want.

<?php echo view_counts(); ?>

Below is the output:

social counter

This is the simple look, you can add CSS and modify layout as your choice.


This post covers following things:

> How to get Twitter and Google API keys

> Created different functions to get social media followers count

> Implemented to cache the count values

> Created method to display counts in HTML format dynamically

Feel free to ask any question in the comments and don't forget to become social follower and share this post if you like.