Showing posts with label twitter. Show all posts
Showing posts with label twitter. Show all posts

Monday, 16 May 2016

6. [How-to] Implement the OnClick of a submit button in a HTML form to post to Twitter via a PHP script

First you will need a web page with a form and input that will allow the user to type the tweet they want to post. I followed this guide: http://www.w3schools.com/php/php_forms.asp
The important part is the action="twitter_post.php". This will tell the form which PHP file to send the tweet to, in order to run the PHP script and post the tweet on the server side.

Here is my sampleform.html file:
 <!DOCTYPE HTML>  
 <html>   
 <body>  
   
   
 <form action="twitter_post.php" method="post">  
 The tweet to post on @deletrius Twitter account: <input type="text" name="tweetpost"><br>  
 <input type="submit">  
   
 </form>  
   
   
 </body>  
 </html>  

As for the twitter_post.php file, this file will need to read the input text of the tweet to post, represented by name="tweetpost". Since we are sending this via POST, we can obtain the value by calling $_POST["tweetpost"] on the server side in our PHP script.

As for the oauth token and oauth secret, you will need to replace those with the ones from yourself, or with the information you received after the oauth authentication shown in my earlier post: http://leadingtechdonkey.blogspot.com/2016/05/2-how-to-integrate-twitter-into-app-in.html

Here is my twitter_post.php file that will take the tweet entered by the user and post it to Twitter:
 <?php  
 require_once 'twitteroauth/autoload.php';  
 use Abraham\TwitterOAuth\TwitterOAuth;  
   
 session_start();  
 $config = require_once 'config.php';  
   
 // connect with user token  
 $twitter = new TwitterOAuth(  
   $config['consumer_key'],  
   $config['consumer_secret'],  
   "REPLACE_WITH_YOUR_OWN_OAUTH_TOKEN",  
   "REPLACE_WITH_YOUR_OWN_OAUTH_SECRET"  
 );  
   
   
 $tweet = $_POST["tweetpost"];  
   
 // post a tweet  
 $status = $twitter->post(  
   "statuses/update", [  
     "status" => $tweet  
   ]  
 );  
 echo ('Created new status with #' . $status->id . PHP_EOL);  
 print_r($status);  
 ?>  
Feel free to leave me a comment below for any clarifications or questions or comments.
[Last updated: 5/16/2016]

5. [How-to] Implement and use Twitter streaming API using PHP

I downloaded the PHP source code and used: https://github.com/fennb/phirehose
Then I uploaded all the folders and files into my PHP server on Arvixe, or you can use 000webhost or x10hosting.

I used the filter-oauth.php file they included as a sample and replace the TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, OAUTH_TOKEN, and OAUTH_SECRET with my own codes from my Twitter developer account.

To get real-time tweets related to specific keywords, change the array of keywords (ie. morning, goodnight, hello, the) to whatever you like in the filter-oauth.php file:
$sc->setTrack(array('morning', 'goodnight', 'hello', 'the'));

To get a random of sample real-time tweets, use the sample.php file and again replace the TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, OAUTH_TOKEN, and OAUTH_SECRET.
To test the real-time streaming Twitter API tweets, open your filter-oauth.php file in a web browser like Google Chrome: http://gerrycao.com/pinkarmr/streaming/example/sample.php

This is my sample.php file:
 <?php  
 require_once('../lib/Phirehose.php');  
 require_once('../lib/OauthPhirehose.php');  
   
 /**  
  * Example of using Phirehose to display the 'sample' twitter stream.  
  */  
 class SampleConsumer extends OauthPhirehose  
 {  
  /**  
   * Enqueue each status  
   *  
   * @param string $status  
   */  
  public function enqueueStatus($status)  
  {  
   /*  
    * In this simple example, we will just display to STDOUT rather than enqueue.  
    * NOTE: You should NOT be processing tweets at this point in a real application, instead they should be being  
    *    enqueued and processed asyncronously from the collection process.  
    */  
   $data = json_decode($status, true);  
   if (is_array($data) && isset($data['user']['screen_name'])) {  
    print $data['user']['screen_name'] . ': ' . urldecode($data['text']) . "<br /><hr />";  
   }  
  }  
 }  
   
 // The OAuth credentials you received when registering your app at Twitter  
 define("TWITTER_CONSUMER_KEY", "REPLACE_WITH_YOUR_OWN");  
 define("TWITTER_CONSUMER_SECRET", "REPLACE_WITH_YOUR_OWN");  
   
   
 // The OAuth data for the twitter account  
 define("OAUTH_TOKEN", "REPLACE_WITH_YOUR_OWN");  
 define("OAUTH_SECRET", "REPLACE_WITH_YOUR_OWN");  
   
 // Start streaming  
 $sc = new SampleConsumer(OAUTH_TOKEN, OAUTH_SECRET, Phirehose::METHOD_FILTER);  
 $sc->setTrack(array('morning', 'goodnight', 'hello', 'the'));  
 $sc->consume();  
 ?>  
   
Feel free to leave me a comment below for any clarifications or questions or comments.
[Last updated: 5/16/2016]

Tuesday, 10 May 2016

4. [How-to] Tweet a new tweet or post using Twitter REST api

You will need to create a twitter_post.php file like the one below and upload it to your server.
As for the oauth token and oauth secret, you will need to replace those with the ones from yourself, or with the information you received after the oauth authentication shown in my earlier post: http://leadingtechdonkey.blogspot.com/2016/05/2-how-to-integrate-twitter-into-app-in.html

My twitter_post.php file:
 <?php  
 require_once 'twitteroauth/autoload.php';  
 use Abraham\TwitterOAuth\TwitterOAuth;  
   
 session_start();  
 $config = require_once 'config.php';  
   
 // connect with user token  
 $twitter = new TwitterOAuth(  
   $config['consumer_key'],  
   $config['consumer_secret'],  
   "REPLACE_WITH_AUTHENTICATED_USER_OAUTH_TOKEN",  
   "REPLACE_WITH_AUTHETICATED_USER_OAUTH_TOKEN_SECRET"  
 );  
   
 // post a tweet  
 $status = $twitter->post(  
   "statuses/update", [  
     "status" => "@deletrius I posted using Twitter REST API! http://leadingtechdonkey.blogspot.com/"  
   ]  
 );  
 echo ('Created new status with #' . $status->id . PHP_EOL);  
 print_r($status);  
 ?>  
   
Feel free to leave me a comment below for any clarifications or questions or comments.
[Last updated: 5/10/2016]

Monday, 9 May 2016

2. [How-to] Integrate Twitter into app in order to view tweets timeline, view user's mentions, post tweets and more!

This is the tutorial I found and used: http://code.tutsplus.com/tutorials/how-to-authenticate-users-with-twitter-oauth-20--cms-25713
It's simple and short.
You definitely should use the TwitterOAuth library to simplify the entire process.
You will need to upload the *.php files to a web server. I use Arvixe which costs money, but you can use the free x10hosting.
I did not use Composer to install the TwitterOAuth. I used the manual way instead.

I also followed the this tutorial to save the user's token and secret into MySQL database: http://code.tutsplus.com/articles/how-to-authenticate-users-with-twitter-oauth--net-13595
I used this tutorial as well to get things going in PHP and for Twitter developer setup: http://iag.me/socialmedia/how-to-create-a-twitter-app-in-8-easy-steps/

This is my config.php file:
 <?php  
   
 return [  
   // key and secret of your application  
   'consumer_key'   => 'REPLACE_WITH_YOUR_OWN_CONSUMER_KEY_FROM_TWITTER',  
   'consumer_secret'  => 'REPLACE_WITH_YOUR_OWN_CONSUMER_SECRET_FROM_TWITTER',  
   // callbacks for your application  
   'url_login'     => 'REPLACE_WITH_YOUR_OWN_URL_LOGIN_EXAMPLE: http://www.gerrycao.com/pinkarmr/twitter_login.php',  
   'url_callback'   => 'REPLACE_WITH_YOUR_OWN_URL_CALLBACK_FROM_TWITTER_EXAMPLE: http://www.gerrycao.com/pinkarmr/twitter_callback.php',  
 ];  
   
 ?>  
   
This is my twitter_login.php file:
 <?php  
 require_once 'twitteroauth/autoload.php';  
 use Abraham\TwitterOAuth\TwitterOAuth;  
   
 session_start();  
   
 $config = require_once 'config.php';  
   
 // create TwitterOAuth object  
 $twitteroauth = new TwitterOAuth($config['consumer_key'], $config['consumer_secret']);  
   
 // request token of application  
 $request_token = $twitteroauth->oauth(  
   'oauth/request_token', [  
     'oauth_callback' => $config['url_callback']  
   ]  
 );  
   
 // throw exception if something gone wrong  
 if($twitteroauth->getLastHttpCode() != 200) {  
   throw new \Exception('There was a problem performing this request');  
 }  
   
 // save token of application to session  
 $_SESSION['oauth_token'] = $request_token['oauth_token'];  
 $_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];  
   
 // generate the URL to make request to authorize our application  
 $url = $twitteroauth->url(  
   'oauth/authorize', [  
     'oauth_token' => $request_token['oauth_token']  
   ]  
 );  
   
 // and redirect  
 header('Location: '. $url);  
 ?>  
This is my twitter_callback.php file:
 <?php  
   
 require_once 'twitteroauth/autoload.php';  
 use Abraham\TwitterOAuth\TwitterOAuth;  
   
 mysql_connect('localhost', 'REPLACE_WITH_YOUR_DB_USERNAME', 'REPLACE_WITH_YOUR_DB_PASSWORD');  
 mysql_select_db('REPLACE_WITH_YOUR_DB_NAME');  
   
 session_start();  
   
 $config = require_once 'config.php';  
   
 // get and filter oauth verifier  
 $oauth_verifier = filter_input(INPUT_GET, 'oauth_verifier');  
   
 // check tokens  
 if (empty($oauth_verifier) ||  
   empty($_SESSION['oauth_token']) ||  
   empty($_SESSION['oauth_token_secret'])  
 ) {  
   // something's missing, go and login again  
   header('Location: ' . $config['url_login']);  
 }  
   
 // connect with application token  
 $connection = new TwitterOAuth(  
   $config['consumer_key'],  
   $config['consumer_secret'],  
   $_SESSION['oauth_token'],  
   $_SESSION['oauth_token_secret']  
 );  
   
 // request user token  
 $token = $connection->oauth(  
   'oauth/access_token', [  
     'oauth_verifier' => $oauth_verifier  
   ]  
 );  
   
 // connect with user token  
 $twitter = new TwitterOAuth(  
   $config['consumer_key'],  
   $config['consumer_secret'],  
   $token['oauth_token'],  
   $token['oauth_token_secret']  
 );  
   
 $user_info = $twitter->get('account/verify_credentials');  
   
 // if something's wrong, go and log in again  
 if(isset($user_info->error)){  
   // Something's wrong, go back to square 1  
   echo "something wrong\n";  
   //header('Location: twitter_login.php');  
 } else {  
    echo "adding new user\n";  
   
     $query = mysql_query("INSERT INTO users (oauth_provider, oauth_uid, oauth_token, oauth_secret, username) VALUES ('twitter', '{$user_info->id}', '{$token['oauth_token']}', '{$token['oauth_token_secret']}', '{$user_info->screen_name}')");  
     $query = mysql_query("SELECT * FROM users WHERE id = " . mysql_insert_id());  
     echo $query;  
     echo "\n";  
     $result = mysql_fetch_array($query);  
     echo $result;  
     echo "\n";  
 }  
 ?>  
Warnings
If you get HTTP 500 - Internal Server Error like me previously.

It's because you already got the $token for the user already! You can't run the twitter_callback.php page for the same user twice! You must save the $token['oauth_token'] and $token['oauth_token_secret'] like to a SQL database or somewhere, and use those two oauth_token and oauth_token_secret from now on, or until the user revoke your application access in his Twitter settings!

I modified my twitter_callback.php to the following for testing after successfully receiving the $token['oauth_token'] and $token['oauth_token_secret'] and then queried for all the user's mentions in Twitter:

 <?php  
 require_once 'twitteroauth/autoload.php';  
 use Abraham\TwitterOAuth\TwitterOAuth;  
   
 session_start();  
 $config = require_once 'config.php';  
   
 // connect with user token  
 $twitter = new TwitterOAuth(  
   $config['consumer_key'],  
   $config['consumer_secret'],  
   "REPLACE_WITH_YOUR_OWN_OAUTH_TOKEN_FOR_AUTHENTICATED_USER",  
   "REPLACE_WITH_YOUR_OWN_OAUTH_TOKEN_SECRET_FOR_AUTHENTICATED_USER"  
 );  
   
 // post a tweet  
 $statuses = $twitter->get("statuses/mentions_timeline", ["count" => 195]);  
   
 //$string = json_decode($statuses, $assoc = TRUE);  
   
   
   
 foreach($statuses as $status) {  
   echo "Time and Date of Tweet: ".$status->created_at."<br />";  
     echo "Tweet: ". $status->text."<br />";  
     echo "Tweeted by: ". $status->user->name."<br />";  
     echo "Screen name: ". $status->user->screen_name."<br />";  
     echo "Listed: ". $status->user->listed_count."<br /><hr />";  
 }  
 ?>  
Feel free to leave me a comment below for any clarifications or questions or comments.
[Last updated: 5/10/2016]

Thank you for not blocking our ads =)

Please consider adding this blog to the whitelist of your ads blocker :)