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.
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.
Scroll down to the Developer Agreement, read it and if you accept, tick the checkbox and click Create your Twitter application.
Note: you must have your phone number saved in your Twitter account device settings, otherwise you will get a warning like the one below.
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.
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