How to update tweet from PHP using Twitter API

twitter-logoTwitter is one popular micro blogging social networking website. ‘Tweet’ of upto 140 characters can be post in twitter. More than 200 million tweets are being twitted every day in the world. For developers it is an unmatchable to others because of its wonderful API which enables us to do almost everything. We can easily update tweets from remote using the twitter API. Here I am going to share how I am updating tweet using this API. I am using PHP programming language for the application.
So, lets get started. First we need to create an application in the Twitter from which we will get credentials which are required later. Login to dev.twitter.com. Under My Applications section, Create a new application is there. Fill up the form with the details. Callback URL is not necessary for our case. Under Application settings, Read and Write options should be selected. Now Click Create my access token button, then we will get Consumer key, Consumer Secret, Access key and access key secret. We need to use that keys later in our code.

Here is the code written in PHP. This is the simplest implementation of twitter API. You can add many features to make it more robust and powerful.

// Including the library 

// Library written by - Matt Harris 

// Twitter id - @themattharris 

// Website - https://github.com/themattharris/tmhOAuth#readme 

require_once('tmhoauth/tmhOAuth.php'); 

// Creating new instance using tokens and keys 

$connection = new tmhOAuth(array(
  'consumer_key' => 'YOUR_CONSUMER_KEY_HERE', 'consumer_secret'
  => 'YOUR_CONSUMER_SECRET_HERE', 

'user_token' =>
  'OAUTH_TOKEN_HERE', 'user_secret' => 'OAUTH_SECRET_HERE', )); 

// Your tweet $my_tweet = 'Hello World'; // API call 

$connection->request('POST',
  $connection->url('1/statuses/update'), array('status' => $my_tweet));

I have used Twitter OAuth library created by Matt Haris in this example. You can pull it from here. Keys and secret tokens should be replaced in the above code which we got from the dev site of Twitter. Text be send is kept in $my_tweet variable here. In our case it is ‘Hello World’.
If you want to learn more then following links would be useful.

Leave a Reply

Your email address will not be published. Required fields are marked *