Project - Social Media App - API's
For my fourth year final project I have undertaken to design a social media web app that will incorporate feeds of Facebook, Google Plus or Twitter into a single feed and allow the user to post their status updates, comments, links and photos or pictures that they wish to share.  I have previously looked at Facebook and Google developer’s pages but never took the plunge in seeing how the dynamics worked or even contemplated to try and attempt to learn how to setup and create connected software to these platforms.  I had always just brushed them off as way past my understanding and ability to create, design or implement a structured piece of software that would be able to integrate with these Social Platforms.  How would I even begin or where to start with assimilating the client side with the server side.  How would I be able to connect the server side and its API’s?  Having only a basic handling of what an API was and some experience of json from the third year project I decided that it would be invaluable to have skills that understand API’s and use them to connect the client with OAuth and receive server side data to which could be manipulated and formatted into a front end application.
The purpose of designing this web app is to have incorporated social feeds integrated into a single feed where the user can post their status updates, comments, links and photos or pictures that they can share from a single point. 
Create a central point where users can share their Social curated world and view/ access their connected friends/ family shared posts
Connect to Facebook by setting up and using software to implement a linked stream.
Connect to Google Plus by setting up and using software to implement a linked stream.
Connect to Twitter by setting up and using software to implement a linked stream.
Extracting the returned stream for individual items and get the data out to screen.
Formatting the returned individual items and style them into posts in a responsive web page.
Figure out how to post a message and a photo/picture image to Facebook, Google Plus and Twitter
By taking two of these social streams combine them into a new stream.
Extract the new stream and style it into a new feed.
Post a single status message to the two social platforms at the same time.
Post a link and comment message to the two social platforms at the same time.
Post a photo/picture image and comment to the two social platforms at the same time.
Find duplicate posts and their timestamps.
To implement a single new post instead of the original two duplicate posts.
Rational for the project
The purpose of the project firstly is to create a social sharing platform that will allow posting of content of status messages, links and photo/ picture images from a central point.  But the logic of being able to learn platform API’s setting up, working with and connecting and accessing the data that then can be used in front end web app. 
To better understand and grasp the dynamics of Facebook, Google Plus and Twitter services the setup of what the services offer, what’s involved with each service how they segregate the information in the service, understanding the departmentalised grouping of the services items.  To understand how API’s flow through hands on connection and implementation of the services and the process of the OAuth using the Id, secret keys from the services to get access tokens to interact with the service and get json feeds. 
When Authenticated through the service using the parameters to access data, requests with data, utilising the data by leveraging / manipulating the json feeds to front end service.  Understanding the platforms and their fundamental concepts and how it all correlates to work with the pieces and how it then binds together to allow flow of data through the API.
API’s are the blueprint for information integration the client server model interface that is becoming the predominant software technology for secure sharing of information through json and xml.  Applications used to use database technology to save and access the data but the major platform companies have turned to API’s as a central point for integrating with the many types of devices such as mobile, tablet, smartphone. Laptops and pc’s to allow communication and data interaction through OAuth 2.0.  Database storage itself has begun to change from just SQL and MySQL to flat design json type data storage such as NoSQL, PostgreSQL, BigQuery, BJSON, MongoDB allowing for more flexibility and speed.  Oracle is still the leading database structure for very large scale companies and will probably remain the backbone for financial, government and contemporary businesses.  But for technology companies the shift to newer software methods for data interaction and ease of implementation and developing for the every changing advancing hardware that will allow software to function on any platform and any device.  API’s working with JSON and XML is a key skill to have in today’s market place in getting into the job placements and work environment to build one’s experience in the technology sector.  The current treat of the openSSL heartbeat or as its name Heartbleed vulnerability in time will be fixed with another tier or level of encryption for security.  Even though the hardware has changed so much over the last few years and software deviates into new routes the one constant is the flow of data between both, manipulation and leveraging of information will always be needed by companies.
Proposed Functionality

Responsive Application
Live Facebook Feed
Live Twitter Feed
Live Google Feed... Stream
Technologies Used
Facebook PHP SDK
Google Plus PHP SDK
Twitter PHP SDK
Twitter Bootstrap
OAuth 2.0 authorization
Sublime Text 2
Laravel PHP Framework
Skills Developed:
Programming in PHP
API programming
Facebook SDK for PHP & Graph API
Google Platform & Google Plus API & PHP
Twitter libraries PHP SDK
OAuth 2.0 protocol authorization flow
Bitly API
JSON Manipulaion
Composer, Symphony, Github, Sublime
For my fourth year project I originally undertook to create a web app using Laravel 4 to create my own API which works with authentication response and requests from two social feeds from their API's.  From Installation of Laravel,  Composer and dependencies such as Symfony Artisan and Monolog and getting to grasp with the running structure of creating items inside Laravel I have created above a  Model View Controller diagram.
Laravel Templating
Sucessfully installed laravel with composer and its dependencies Symfony Artisan and Monolog and set about understanding templating using MVC and @extends @section and @yield includes for laravel. Below is a running working example using routes views and controllers and how the dynamics of connection works
Project Steps
1. Facebook PHP SDK
getting a basic connection to Facebook by setting up the keys and secret in the console panel
and using the code with specific settings.  base_facebook.php - change the login and logout url in the functions getLogoutUrl and getLoginStatusUrl to correct login logout Urls for project.  Set the Page tabs settings so the URI from the page would match the URL on the facebook console app page to allow the redirect and OAuth process to make the link to pass the Id’s and secret and get the Access token and start the session with Facebook.
When Facebook authenticates it then gets the $user which is a unique id for the User which will be the user id of the person logged in and authenticated through the OAuth process in this app.  The next step was in being able to set the right FQL(Facebook Query Language) this was done from research and in the Graph API explorer tool (
$user_profile = $facebook->api('/me?fields=id,name,feed');
Here I set the FQL to request the ID name and their feed.
When authenticated with OAuth over the web the process is that Facebook sends the unique appId and secret to their API and verifies them and then creates a Access Token which is then set into a facebook session where the Access token can be used to verify communication and find the details to the queries sent by FQL and the scope.
To check that this was implemented I did a check by printing the details out to screen with some php: also in the console panel in chrome browser under resources in local storage and cookies more detailed of live session details.
<!-- <?php print_r($_SESSION) ?>  // Check the Session   --> 
Once that had worked the next stage is to check that the user is logged in or not logged in by checking the $user variable thus setting the login button or log out button depending on the status of the $user variable.
The next stage was accessing more details for the user logged in, I could echo out the basic details of the user with print_r to view the unique ID and the uername.
      <!-- <pre><?php print_r($user); ?></pre> -->
I progressed with using a simple FQL to ger more details as the first name last name and the users profile picture to be able to show them on screen.
  <?php $result = $facebook->api('/me');
               $idUser = $user; // get the user id and set it to new variable to use with feed if needed
                        //echo  $user;
                        $first_name = $result['first_name'];
                        $last_name = $result['last_name']; ?>
     <p>  <img src="<?php echo $user; ?>/picture">  <?php       echo " ".$first_name ." ". $last_name ?> You are now logged In </p>
      <!--  User Id is Printed to screen -->
From the research and understanding I choose the scopes and permissions that I needed to work with this web app that would allow me to access the information and get the feed that I needed to then start to access into the data and get it to the screen.
From the research and understanding I choose the scopes and permissions that I needed to work with this web app that would allow me to access the information and get the feed that I needed to then start to access into the data and get it to the screen.
  <?php $loginLink = $facebook->getLoginUrl(array('scope' => 'email','manage_notifications','user_likes','read_stream','publish_actions','publish_stream',
user_videos,user_photo_video_tags,user_photos')); ?>
 <?php $resfeed = $facebook->api('/me/feed');  ?>
I could now get back a json feed and simply print it out to screen:
<pre><?php print_r($resfeed); ?></pre>
Having the bulk unstyled json feed on the screen my next challenge was to pluck the items out and get the different items into a post. I set a variable to get the number of Facebook posts where I then could loop through and echo out the items into a post to the screen.
$number = count($resfeed['feed']['data']);
for ($i = 0; $i < $number; $i++)
            echo '<div class="feeds">';
            echo '<div class="feedbox">';
            echo '<div class="feedboxtop">';  
    echo '<img src="'.$user.'/picture" width="50px" height"50px" class="circular" style="float:left;" >';
            echo '<a href="'.$resfeed["feed"]["data"][$i]["link"].'"  >'.$resfeed["feed"]["data"][$i]["link"].'</a> ';
            echo '</div>';
            echo '<div class="feedboxright">';
            echo '<div class="feedboxleft">';
    // echo $resfeed["feed"]["data"][$i]["picture"] ;
            $image = $resfeed["feed"]["data"][$i]["picture"];
            echo '<img src="'.$image.'"  style="float:left;margin: 0px 0px 0px 0px" />';
            echo '</div>';
            echo '<div class="innerbox">';
            echo '<a href="'.$resfeed["feed"]["data"][$i]["link"].'"  >'.$resfeed["feed"]["data"][$i]["link"].'</a> ';
            echo  $resfeed["feed"]["data"][$i]["message"];
            echo '</div>';
   echo '</div>';
   echo '<div class="descriptbox"> '; 
                                    echo  $resfeed["feed"]["data"][$i]["name"] ;
                echo '</p>';
                        echo  $resfeed["feed"]["data"][$i]["description"];
            echo '</div>';
            echo '<div class="postend" >Posted by '. $first_name ." ". $last_name ; echo'  </div>';
            echo '</div>'; // <!-- End of Feedbox class-->
            echo '</div>'; // <!-- End of Feeds class -->
2. Google Plus PHP SDK
I downloaded the SDK and connected it into the appropriate folders in the project and also setup the connection with the Id’s and secret in the google app console and also configured the redirect URI page which corresponds to the $client->setRedirectUri page to sync the OAuth connection to communicate.
I required the src/Google_Client.php and src/contrib/Google_PlusService.php classes and started a new google client where the Id, secret and developer keys are inserted to allow the OAuth to get the access token when authenticated over the web.
$client = new Google_Client();
$client->setApplicationName("Google+ PHP Starter Application");
$client->setClientId(CLIENT_ID in here );
$client->setClientSecret(CLIENT SECRET in here );
$client->setRedirectUri('');  // this has to match the URL direct in the google console app panel
$client->setDeveloperKey(DEVELOP KEY in here);
$plus = new Google_PlusService($client);  // this sets the service for Google
In the src/config.php file the Id, secret and developers key needs to be set and the scope for google plus login is in that config.php file for the api request.
   'plus' => array('scope' => ''),
In the src/Google_Client.php other classes are required to facilitate the connection to google these are top level classes such as Google_Auth.php and  Google_Service.php.  When the connection happens over OAuth a access_token is sent back and the request details are setup along with the access tokens to connect to the specific activity in Google Plus
  $activities = $plus->activities->listActivities('me', 'public', $optParams);
In the $client request details there is the $personMarkup for the details of the users name, url and users image that is in correspondence to the $activities ( settings of ‘me’ to be able to fetch the scope and  details of the feed.
  $personMarkup = "<a rel='me' href='$url'>$name</a><div><img src='$img'></div>";
An if isset is done on the $authUrl and access token to make sure the OAuth session is there and also an if isset done on the $personMarkup to make sure they are logged in if this is not the case then the login button will be presented.
The json feed was now available once you had logged in through OAuth over the web in the variable $activity.  I then used a for each loop to access the individual elements and styled the post to output to front web page. At the present time with PHP Google Plus is read only.
3. Twitter PHP SDK's
In realising Google Plus was read only I needed another social platform to be able to continue with the project so I jumped in and decided to get Twitter going with its API and connect to it as an alternative that would allow social posting. I went to twitter developer and created the app and configured the settings to get the API key and secret, access token and access token secret and downloaded the API PHP twitteroauth ( to work with and get connected through OAuth.
I put the library class files into the connect folder in twitteroauth folder where i inserted the API and access secret and tokens in the config.php file and set the OAuth callback where the new access token is set into a session variable to be used with twitter requests for the feed.
     define('OAUTH_CALLBACK', '');
In the callback.php file it also checks or verifies the session is there and if not it redirects you to clearsessions.php where all twitter sessions are destroyed and then sends you back to the login page to login to twitter again.
In a new page to implement the twitter feed i required config.php and twitteroauth.php to access the libraries and keys and secrets.  The twitteroauth.php file requires the OAuth.php file which manages the OAuth requests and processing to the twitter API and the twitteroauth.php utilises the requests with the tokens, secrets and access token that is sent back. In the main twitter page set up i inserted the code to connect which checks if the keys and secrets are set and then a login to twitter button is created.  A check is done first to see if the session access token is there and if not echo a login button and if it is set echo a logout button
Then if the session access token is set put it into a variable then a request is setup with the keys and secret and the new access token details and a get request is sent to twitter API to get the users timeline json feed
/* Get user access tokens out of the session. */
$access_token = $_SESSION['access_token'];
/* Create a TwitterOauth object with consumer/user tokens. */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
$user = $connection->get('statuses/home_timeline');
I had to encode and decode the $user json feed that came back from twitter to be able to use a for each loop to get the individual items out to screen into posts.
$twitfeed = json_encode($user);
$string = json_decode($twitfeed, true);
foreach($string as $items)
                echo '<div class="holder">';
                echo '<img src="'.$items['user']['profile_image_url'].'" class="circular" style="float:left;" >';
        echo  "<p style='padding:0px;color:#ccc;margin:0px;'>".$items['created_at']."<br /></p>";
                        echo "Name: ".$items['user']['name']." &nbsp;";
                        echo "@".$items['user']['screen_name']."<br />";
                        echo 'Website: <a href="'.$items["user"]["url"].'" target="_blank" >'.$items["user"]["url"].'</a> ';
                        echo'<br />';
                echo '<div class="tweetbox">';      
        echo " &rArr;&nbsp; ". $items['text']."<br />";
                        echo "</div><br />";
       // echo "Tweeted by: ". $items['user']['name']."<br />";
       // echo "Screen name: ". $items['user']['screen_name']."<br />";
        echo "Followers: ". $items['user']['followers_count']."&nbsp;&nbsp; Friends: ". $items['user']['friends_count']."&nbsp;&nbsp; Listed: ". $items['user']['listed_count']."<br />";
       // echo "Friends: ". $items['user']['friends_count']."<br />";
       // echo "Listed: ". $items['user']['listed_count']."<br />";
                        echo "</div>";
                        echo'<br /><br />';
Posting to Facebook
I required the src/facebook.php' file to allow connection to Facebook API to check OAuth and a request array is configured with the appId and secret for API request to Facebook.
$config = array(
  'appId'  => 'xxxxxxxxxxxxxxx',
  'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    'allowSignedRequest' => false // optional but should be set to false for non-canvas apps
This is set into Facebook method into a variable where it calls the get method for the User logged into Facebook through the session and access token and put into a $user_id variable
$facebook = new Facebook($config);
  $user_id = $facebook->getUser();
An if statement then checks for this $user_id and if it’s there a new post request is created to facebook api for the scope /me/feed with the details of what’s to be posted inside an array which is the message where the variable from the form $status is set into ‘message’ to be sent
if($user_id) {
      try {
        $ret_obj = $facebook->api('/me/feed', 'POST',    // http request for post to users feed
             'message' => $status // sets the status message into facebook message into array
If the request was successful a variable was set $success and a redirect back to the feed page was done and if not the error or exception would be printed to screen with the login button if the user was not logged in or there was no access token.  From coding attempts and research I had found out that I needed to turn output buffering on to allow posting from php to facebook to work ob_start(); // turn output buffering on.  I now had a single message going to Facebook from the posting panel on the facebook page.
I then setup uploading an image to the server to allow fetching of image to posting an image and message on facebook.  I set the $photo into the $target_path variable and again if the access token is set in the session and the $user_id is found the file on the server is then uploaded and in the request POST API array source is set to the $target_path and the message is set to $message and these are then posted to Facebook and an Photo ID is given to every individual uploaded photo again I did a check by echoing out the successful result and if the picture wasn’t upload an error message is echoed out to screen and link back to the posting page.
$target_path =  $photo ;
if($user_id) {
                                    move_uploaded_file($_FILES['photo']['tmp_name'], $target_path); // move the file to the location on server
$ret_obj = $facebook->api('/me/photos', 'POST', array(
                                         'source' => '@' . realpath($target_path),
                                         'message' => $message,// set the message into facebook message
        echo '<pre>Photo ID: ' . $ret_obj['id'] . '</pre>'; // echo the photo Id from facebook to check it has worked
        // echo '<br /><a href="' . $facebook->getLogoutUrl() . '">logout</a>';
                        echo $message ;
Posting to Twitter
I required_once the library file twitteroauth.php and the config.php with the configuration keys and secrets to then firstly check that the twitter session access token/oauth token/oauth token secret are set from the twitter login and if not it is sent to the clearsessions.php file to empty the session and then redirected back to the login page for twitter.  If the user is logged in and the session details are set the keys and secrets are got from the config.php file and set into a variable and from there a new Get request is setup and sent to twitter account to verify credentials and verify the access token/oauth token which would allow for the next step for a Post request.
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_SECRET); // get the keys and secret from comfig.php file
$content = $connection->get('account/verify_credentials'); // request to verify access token and oauth token
The Post request is directed to statuses update to the users stream with the details set into an array of the information to be sent.  The form input was named status and this was then set into a variable when sent from the form $status = $_POST["status"];.  The $status is then set in the Post array to the ‘status’ for twitter but also from research and coding the time and date (date(DATE_RFC822)) is needed to successfully allow the post to happen.
$connection->post('statuses/update',  // request to post to update the users stream
'status' => date(DATE_RFC822),  // date time of post
'status' => $status                                            // status message into the array
) );
To check that this was successful I had echoed out the $content and $connection to view the details of the process of what was being passed and if it was successful with status 200 code.
For the link and message to twitter the exact same process was used and the link and message where concatenated into the $status variable and set into the Post array to be sent to the status update to twitter users stream.
$status = $_POST["link"].' '.$_POST["message"]; // combine the link and message to send as a single line tweet
For posting an image and message I used twitteroauth API and trying variations on coding again led me to using the image from the form rather than on the server using the $file_type for what type of image it was (.jpeg, .png) and its name $file_temp along with just ‘true’ to use authentication for posting the image.
$content = $connection->post('statuses/update_with_media',
'media[]' => "@{$photo};type={$file_type};filename={$file_temp}",
'status' => $message),
true);  // Use Auth for posting image
Bitly API - Shortlink
I set up the bitly app details with the client Id and secret the generic access token and got the API key and downloaded the library files (, Falicon bitlyphp) to use with these items, I then placed the libraries in the folder and required_once the bitly.php in the main page.  In the bitly.php file I inserted the client Id and secret and API Key and went to the documentation for bitly OAuth Authentication
( to get connected to get back the access token which would be saved into a session.  I created and echoed out the link request with the client Id and the uri parameter to allow connection which would give me back the ‘code’ or access token in a session when authenticated and signed in to bitly.
echo'    <a href=""><img src="../assets/images/bitlyblackbutton.png" width="190px" height="36px" style="margin: 0px 0px 6px 130px;"><!--Authorize bitly Shortener--></a>'
if bitly authorised I could then get the ‘code’ back with ($_REQUEST['code'] and then access the returned values to use in shortening the longlink.
  if( $results = bitly_oauth_access_token($_REQUEST['code'],
'') ) // URL to direct back to
I then put these returned values into new variables and set them into session variables
$accesstoken = $results['access_token'];
$x_login = $results['login'];
$x_apiKey = $results['apiKey'];
$_SESSION['accesstoken']= $accesstoken;
$_SESSION['x_login']= $x_login;
$_SESSION['x_apiKey']= $x_apiKey;
I then needed to figure out how to use the access token and longlink to acquire a shortlink so I went to bitly documentation for shorten request ( to understand how to make this happen.  I accomplished this by inserting the $accesstoken and $longurl (which was just set as a single longlink but later I used the input from a single form and pushed this into a session array) into the request url which I used simple curl session to initialise send and return from bitly the json with the details of the shortlink.
$ch = curl_init(''.$accesstoken.'&longUrl='.$longurl.'&format=json');
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$bitlyresult = curl_exec($ch);  // set the returned curl json into variable
$json = @json_decode($bitlyresult,true);  decode the json array
$shortlink = $json['data']['url'];  // set the link into variable
I then used this $shortlink in the posting forms and set it as the value in the form fields.
Facebook & Twitter Combined Stream
I created temporary arrays in the JSON feed for both facebook and twitter and using a for i loop pushed them into a new array for new feed.
When I was pushing the twitter and Facebook feeds into the new array fed  I set in the second slot a number to identify the type of post: 
                                                      1  =  Facebook Post
                                                      2  =  Twitter post
I also pushed the timings into epoch timings from the original json feeds in facebook and twitter with strtotime() into the new feed array.
I used a foreach loop to grab the slot with the epoch time and set it as a variable $time where I then used array_multisort() on $time sorting descending on the  new array new feed to get the most recent post to be on top of the list in the feed.
foreach ($newarray as $key => $row)
    $time[$key]  = $row['0'];         
array_multisort($time, SORT_DESC, $newarray);
I then set about to figure out how to find the duplicate posts with matching epoch time + or - 5 seconds. Using arrays to compare against arrays and to verify that it is a duplicate - view example code below:
if( $row['1'] == 1 || $row['1'] ==  2) // if identifier is equal to facebook or twitter
                     $num = sizeof($facearray); // get the lenght of twitarray time
                     $length = sizeof($twitarray); // get the lenght of facearray times
     for($j = 0; $j < $num; $j++) // loop through twiter
          for($m = 0; $m < $length; $m++) // loop through facebook
                       $difference = $facearray[$j] - $twitarray[$m];
              if($difference < 0)
                    $difference *= -1;  // switch to a positive number
             if($difference < 5)
                  $twitarray[$m].$duplicate = true; // if it is a duplicate set to true
                  $dupfacepost = $twitarray[$m]-1;  // push into facebook variable to use
                  $duptwitpost = $twitarray[$m];    // push into twitter variable to use
array_push($dupfacetime, $dupfacepost); // push the matching time into array for facebook
array_push($duptwittime, $duptwitpost); // push the matching time into array for twitter
I then using array_diff() compared the $dupfacetime array and the $duptwittime array against $fooblearray[‘0’] epoch timings to verify the correct duplicate timings and these where set into new arrays for the verified duplicates $facedup and $twitdup.
                         $facedup = array_diff($dupfacetime, $fooblearray['0']);
                         $twitdup = array_diff($duptwittime, $fooblearray['0']);
Then inside the for each loop to access the $newarray feed items after the duplicate if loop inside if ($row['1'] == 1) where 1 is facebook posts I put a new if statement to check if the facebook post times duplicates where equal to time in the $newarray to then allow echoing the new foobleit post instead of the facebook post
       if(($facedup['0'] === $key = $row['0']) | ($facedup['1'] === $key = $row['0'])
and then did the same in the if ($row['1'] == 2) where 2 is twitter and put a new if statement to check if the twitter post time duplicates where equal to time in the $newarray and if they were not to post anything
       if( ($twitdup['0'] === $key = $row['0']) | ($twitdup['1'] === $key = $row['0'])
if there were no duplicates the normal facebook and twitter posts would be echoed out to screen.
Assessment of process
Understanding the different platforms and their fundamental concepts and how it all correlates to work with the pieces and then binds together to allow flow of data through the API.
What did you gain from the Project:
1.      Understanding dynamics of Facebook, Google Plus, Twitter
2.      How API allows flow information and feeds
3.      Process of OAuth using Id, secret, keys to get access token
4.      Using the parameters to access data, requests with data, utilising the data
5.      Leveraging/Manipulating data through JSON
6.      Pulling and pushing data from API
7.      Using arrays and sessions in php
8.      API is the blueprint for information integration - client server model interface
Project - Social Media App - API's

Project - Social Media App - API's

For my fourth year final project for Honours Degree in IT Creative Multimedia in LIT, I created a social media web app that incorporated feeds of Read More
Copyright Info

Attribution, Non-commercial

Read More