Tuesday, July 16, 2013

How to post a tweet from website using PHP

Twitter has updated their API from 1 to 1.1 where we needed a code for posting tweets from our website. I searched lot of codes but finally came across this one here.

We first need to create a twitter application here. Sign in with your twitter account. After creating a application, you ll get your access token, access secret, consumer key and consumer secret. Make sure, that your application is on read and write permission.



ini_set('display_errors', 1);
require_once('TwitterAPIExchange.php');

/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
    'oauth_access_token' => "your app access token",
    'oauth_access_token_secret' => "your app access secret",
    'consumer_key' => "your app consumer key",
    'consumer_secret' => "your app consumer secret"
);

/** URL for REST request, see: https://dev.twitter.com/docs/api/1.1/ **/
$url = 'https://api.twitter.com/1.1/statuses/update.json';
// $url = 'https%3A%2F%2Fapi.twitter.com%2F1.1%2Fstatuses%2Fupdate.json';
$requestMethod = 'POST'; 

/** POST fields required by the URL above. See relevant docs as above **/
$postfields = array(
    'status' => 'Maybe', 
);

/** Perform a POST request and echo the response **/
$twitter = new TwitterAPIExchange($settings);
echo $twitter->buildOauth($url, $requestMethod)->setPostfields($postfields)->performRequest();    

Download the code from github here.

3 comments:

  1. Im getting this:
    Fatal error: Uncaught exception 'Exception' with message 'You need to install cURL, see: http://curl.haxx.se/docs/install.html' in /var/www/html/tweet/TwitterAPIExchange.php:76 Stack trace: #0 /var/www/html/tweet/index.php(21): TwitterAPIExchange->__construct(Array) #1 {main} thrown in /var/www/html/tweet/TwitterAPIExchange.php on line 76

    ReplyDelete

ShareThis