Auto Post on Twitter Using PHP and API 1.1



As Twitter provides an API to communicate with it so you need user Access Tokens and Consumer Keys of a Twitter App to Auto Post on Twitter. In my previous tutorial How to Auto Post on Twitter Using PHP ā€“ Part 1, I have described how you can create an App and get the Consumer Keys and Access Tokens. In this Tutorial I as explaining how to auto post on twitter using PHP and twitter API.

PHP Library

There are so many twitter libraries available in PHP, you can pick any one as you like. I have used TwitterOAuth, this is simple class, that support OAuth for Twitter’s REST API, downloaded from https://github.com/abraham/twitteroauth.

TwitterOAuth Requirements
1. PHP 5.3.0 or higher
2. php CURL extension
3. php OpenSSL extension

Post a simpleĀ  text tweet using PHP
Following is a simple example of share a status on twitter using PHP.


require_once("Twitter/autoload.php");

use Abraham\TwitterOAuth\TwitterOAuth;

$tw = new TwitterOAuth(consumer_key, consumer_secret, oauth_token, oauth_token_secret);
$content = $tw->get("account/verify_credentials");

if(strlen($status) > 140) {
	$status = substr($status, 0, 140);
}

$tw->post('statuses/update', array(
	'status' => $status
));

You can tweet the length of 140 characters only, as twitter has characters limit of 140, so in above example I have shorten the message.

Post Image with text tweet using PHP

If you want to upload image with text tweet, you can do this as follow:

require_once("Twitter/autoload.php");

use Abraham\TwitterOAuth\TwitterOAuth;

$tw = new TwitterOAuth(consumer_key, consumer_secret, oauth_token, oauth_token_secret);
$content = $tw->get("account/verify_credentials");

if(strlen($status) > 140) {
	$status = substr($status, 0, 140);
}

$media1 = $tw->upload('media/upload', array('media' => 'C:/xampp/htdocs/How-to-Auto-Post-on-Twitter-Using-PHP.png'));

$tw->post('statuses/update', array(
	'status' => $status,
        'media_ids' => implode(',', array($media1->media_id_string))
));

You will see result as below on your twitter page.

example of auto post on twitter using PHP
example of auto post on twitter using PHP

Now you can this process with controlled via database and cron to post automatically on twitter. Hope this tutorial will help you to Auto Post on twitter using PHP and API 1.1.