Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

Twitter is a great way to share content and with the use of the TwitterOAuth, a Twitter OAuth REST API PHP library, adding twitter functionality to your PHP project is easy as pie. I've recently added Twitter auto-post functionality to my blog software and wanted to share my notes. My goal was to be able to tweet directly from my blog admin pages, so this entry shows how to set up your own Twitter App, how to establish a connection with Twitter and to sent message and photo tweets using your own Twitter account.

This example uses the Single-user OAuth functionality since the intent is to publish content to Twitter from the author's Twitter account. There is no need to authenticate/authorise an external Twitter user. This way, the access tokens are generated once and used multiple times. It is expected these are either defined in the code or stored somewhere on the server's file system.

To get started, a Twitter App needs to be created from the Application Management page. Use the Create New App button.
twitterapp_1.png


Then fill in your Apps'd details, for example, this is what I used for my blog. The Callback URL is not necessary for this example.
twitterapp_2.png




Scroll down to the Developer Agreement, read it and if you accept, tick the checkbox and click Create your Twitter application.
twitterapp_3.png


Note: you must have your phone number saved in your Twitter account device settings, otherwise you will get a warning like the one below.
twitterapp_4.png


Now that the app is created, you will have the consumer key and consumer secret, however you need to generate an access token manually. This is done from the Application Management by clicking on your app and then clicking the Keys and Access Tokens tab. Once there, click the Create my access token button and refresh the page to access the token.
twitterapp_5.png

twitterapp_6.png


At this point you should have the following recorded:
  • Consumer key
  • Consumer secret
  • Access token
  • Access token secret


In the code, I will refer to these like this (make sure to use your own values below, in my actual blog code, this is stored with the rest of the settings, but for this example, it will be hard-coded):
 Twitter Settings
$twconsumerkey = 'someconsumerkey';
$twconsumersecret = 'someconsumerkeysecret';
$twaccesstoken = 'someaccesstoken';
$twaccesssecret = 'someaccesstokensecret';


The next step is to get the Twitter OAuth library from its GitHub page, unpack it into your project and add the following code to have it loaded (adjust paths as necessary).
 Twitter OAuth Loading
require_once 'lib/twitteroauth-0.5.3/autoload.php';
use AbrahamTwitterOAuthTwitterOAuth;


Now comes the fun part, checking if you can successfully connect to the Twitter API. I like to have a function to make sure that it is possible to post to Twitter first, before actually trying to post to it. Here it is:
 Checking if posting to Twitter is possible
function isTwSessionValid() {
global $twconsumerkey, $twconsumersecret, $twaccesstoken, $twaccesssecret;
$connection = new TwitterOAuth($twconsumerkey, $twconsumersecret,
$twaccesstoken, $twaccesssecret);
$connection->get("account/verify_credentials");
if ($connection->getLastHttpCode() != 200) {
return false;
}
return true;
}


This function is very straight forward, it uses the previously defined variables for the consumer key, access token, etc. A connection is set up and a GET call is made to account/verify_credentials. If the return HTTP code is 200, you can post to Twitter.

Now the next function does the actual posting to Twitter. It requires a message, a URL and an image path passed into it. The message is what will actually be posted to Twitter a.k.a. the tweet. The post URL is the URL to associate with the post, for example if sharing a blog post URL via the Tweet; this is making use of Twitter's objects entities. The imgpath variable is an optional path on the server to an image that will be uploaded to Twitter and associated with the tweet message.
 Posting a message and optionally an image to Twitter
function postToTw($message, $posturl, $imgpath) {
global $twconsumerkey, $twconsumersecret, $twaccesstoken, $twaccesssecret;
$do_upload = false;
if (file_exists($imgpath)) {
$do_upload = true;
}
$connection = new TwitterOAuth($twconsumerkey, $twconsumersecret,
$twaccesstoken, $twaccesssecret);
$parameters = array(
'status' => $message,
'urls' => array('expanded_url' => $posturl)
);
if ($do_upload == true) {
$media1 = $connection->upload('media/upload', array('media' => $imgpath));
$parameters['media_ids'] = $media1->media_id_string;
}
$connection->post('statuses/update', $parameters);
if ($connection->getLastHttpCode() != 200) {
return false;
}
return true;
}


The function makes use of the previously defined consumer and access tokens again. It creates a new connection to Twitter, creates the parameter array for the statuses/update call, optionally uploads an image and then makes a call to post the new status message. Similarly to the previous function, a return code of 200 means that the tweet was successful.

That's all there is to it, nice and simple!

-i

A quick disclaimer...

Although I put in a great effort into researching all the topics I cover, mistakes can happen. Use of any information from my blog posts should be at own risk and I do not hold any liability towards any information misuse or damages caused by following any of my posts.

All content and opinions expressed on this Blog are my own and do not represent the opinions of my employer (Oracle). Use of any information contained in this blog post/article is subject to this disclaimer.
Hi! You can search my blog here ⤵
NOTE: (2022) This Blog is no longer maintained and I will not be answering any emails or comments.

I am now focusing on Atari Gamer.