The easiest way to Post Tweet using Twitter API v1.1 in PHP and without cURL! 2 Steps to Post Tweet using PHP, without Abraham Library!.
How to Post Tweet using PHP
We need Twitter App and QassimPostTweet Script, download it.
Create Twitter App
Go to Twitter App and create a new App, after that open your App and go to “Permissions” tab:
Choose “Read and Write” Permission.
Open “Keys and Access Tokens” tab and click on “Create my access token” button:
Post Tweet
Use QassimPostTweet Script to Post Tweet:
/* QassimPostTweet Script Written By: Qassim Hassan. Twitter: @QQQHZ Website: wp-time.com */ /* Keys and Access Tokens */ $consumer_key = 'XXXXXX'; // Enter your consumer key. $consumer_secret = 'XXXXXX'; // Enter your consumer secret. $access_token = 'XXXXXX'; // Enter your access token. $access_token_secret = 'XXXXXX'; // Enter your access token secret. /* Create Base String */ function BaseString($url, $parameters){ $get_url = rawurlencode($url); $string = array(); ksort($parameters); foreach ($parameters as $key => $value) { $string[] = "$key=" . rawurlencode($value); } return "POST&".$get_url."&".rawurlencode(implode('&', $string)); } /* Post Tweet */ function PostTweet($consumer_key, $consumer_secret, $access_token, $access_token_secret, $tweet){ $parameters = array( 'oauth_consumer_key' => $consumer_key, 'oauth_nonce' => time(), 'oauth_signature_method' => 'HMAC-SHA1', 'oauth_timestamp' => time(), 'oauth_token' => $access_token, 'oauth_version' => '1.0', 'status' => $tweet ); $base_string = BaseString("https://api.twitter.com/1.1/statuses/update.json", $parameters); $composite_key = $consumer_secret."&".$access_token_secret; $oauth_signature = base64_encode(hash_hmac('sha1', $base_string, $composite_key, true)); $parameters['oauth_signature'] = $oauth_signature; $options = array('http' => array( 'method' => "POST", 'header' => "Content-Type: application/x-www-form-urlencoded\r\n", 'content' => http_build_query($parameters) ) ); $context = stream_context_create($options); $result = file_get_contents("https://api.twitter.com/1.1/statuses/update.json", false, $context); $json = json_decode($result, true); return $json; } /* Post your tweet */ $tweet = 'My first Tweet using @TwitterAPI and QassimPostTweet.php Script by @QQQHZ'; // Enter your tweet text! $result = PostTweet($consumer_key, $consumer_secret, $access_token, $access_token_secret, $tweet); echo 'Tweet is posted! <a href="https://twitter.com/'.$result['user']['screen_name'].'/status/'.$result['id_str'].'" target="_blank">Your Tweet Link</a>'; /* Display JSON Array */ //echo '<pre>'; //print_r($result); //echo '</pre>';
Enter your Keys and Access Tokens, and in the variable “$tweet” enter your Tweet Text.
Enjoy.
1 Comment
hicks
Hi Qassim, this works great, thanks a lot.
What if you need to add an image? How you add it to the tweet?
thanks!