How to Post Tweets Using PHP : Twitter API Part 2

Few months back, I posted an article on Twitter API and explained how to login using Twitter API and PHP. In that article, I just talked about login and getting Twitter access token. In this tutorial, I will take the series ahead to tell you how to do more things on Twitter using Twitter API.
If you have not read the old article, you should read it first. I will not repeat how to get access token again. And access token will be needed to post a Tweet.
In previous article, I talked about a config.php file that contained consumer key and secret. It will be same in this as well.
$CONSUMER_KEY='Your Consumer API Key'; $CONSUMER_SECRET='Your Consumer API Secrent'; $OAUTH_CALLBACK='Call back URL';
twitteroauth.php will also be needed here. We obtained twitter_token and twitter_secret In previous article. The method of obtaining and saving in the database will be same.
Post tweet with image
Now you just need the following code to post a new tweet.
$connection = new TwitterOAuth($CONSUMER_KEY, $CONSUMER_SECRET, $row['twitter_token'], $row['twitter_secret']); $msg = 'Google confirms Android O. Developer Preview is now available. Details here: https://goo.gl/fb/E1NFKq #AndroidO #techlomedia'; $content = $connection->get('account/verify_credentials'); $connection->post('statuses/update', array('status' => $msg));
This code will publish a new Tweet and will return the Tweet id.
Post tweet with image using PHP
If you want to upload an image, this is also easy. You can upload media files on Twitter via API as well. But there is a size restriction. You can upload a photo of up to 5MB or GIF file of up to 15MB.
$image = 'PATH OF IMAGE FILE' $connection = new TwitterOAuth($CONSUMER_KEY, $CONSUMER_SECRET, $row['twitter_token'], $row['twitter_secret']); $msg = 'Google confirms Android O. Developer Preview is now available. Details here: https://goo.gl/fb/E1NFKq #AndroidO #techlomedia'; $content = $connection->get('account/verify_credentials'); $connection->post('https://upload.twitter.com/1.1/media/upload.json', array("media_data" => $image);
Final Words
Now you know how to use PHP and Twitter API to post a new tweet. This code will work until Twitter decides to change something. I have tested this code before posting here. If you still find it hard to implement this, you can always leave a comment.
Leave a comment
Comment policy: We love comments and appreciate the time that readers spend to share ideas and give feedback. However, all comments are manually moderated and those deemed to be spam or solely promotional will be deleted.