Posted by on Jun 18, 2013 in Blog

Even the code and examples on twitter API documentation is straight forward but It wasn’t easy to figure out the right code with twitter API for tweet images. After few hours of searching and looking into code example, I managed to crack the code with the help of some external library. My problem while I’m trying to tweet images was with the use of temporary access token to post a tweet with image and never exchange it with correct access token using twitter API. For that reason I thought of writing this blog with clear steps to help anyone who is stuck with same problem of tweet images using twitter API.

Twitter APICreating Twitter App

To create twitter application you need to do that from : https://dev.twitter.com/

In twitter dev site, you have to specify the name and decryption of your application plus the URL to your main page and the callback page (more on these two page later). Also you have to make sure you set your twitter application access to “Read and Write” in order to give it authorization to tweet images on user behalf.

After the app is created correctly, twitter will provide you with a “Consumer key” and “Consumer secret”, you need to keep these two string variables because they are required to identify your application while communicating with twitter API to tweet images.

Download twitter code libraryDownload the Required PHP Libraries

For twitter authentication and image uploading to twitter you need tmhOAuth.php and tmhUtilities.php you can download them from https://github.com/opauth/twitter/tree/master/Vendor/tmhOAuth

How the Tweet Images Code Works?

The code for tweet images divided in two files, the first is “start.php” where the code start and a second file “callback.php” where twitter will redirect user back after giving authorization to our app. (the URL to our callback.php file has been updated in App settings in steps above)

How the code works

1. In “start.php” the first thing we have to do is asking for temporary access token from twitter API using the key and secret that we get them when we create the application (this process call get request token).

$tmhOAuth = new tmhOAuth(array(
 'consumer_key' => API_KEY,
 'consumer_secret' => API_SEC, 
 'curl_ssl_verifypeer' => false
 ));
 $tmhOAuth->request('POST', $tmhOAuth->url('oauth/request_token', ''));
 $response = $tmhOAuth->extract_params($tmhOAuth->response["response"]);

2. After we have the temporary access token we need to save them in cookies for later use after the user authenticate our App and redirected back to “callback.php”.

$temp_token = $response['oauth_token']; 
$temp_secret = $response['oauth_token_secret']; 
$time = $_SERVER['REQUEST_TIME'];
setcookie("Temp_Token", $temp_token, $time + 3600 * 30, '/twitter_test/');
setcookie("Temp_Secret", $temp_secret, $time + 3600 * 30, '/twitter_test/'); setcookie("Tweet_Txt", $txt, $time + 3600 * 30, '/twitter_test/');
setcookie("Img_Url", $img, $time + 3600 * 30, '/twitter_test/');

3. Asking user to give authorization to our app requires a redirect to Twitter API page where user will fill his username and password and complete the authorization process.

$url = $tmhOAuth->url("oauth/authorize", "") . '?oauth_token=' . $temp_token;
header("Location:".$ url);
exit();

4. When authorization is been given to our app, Twitter API will redirect the user to “callback.php” URL specified in App settings.

5. In “callback.php” file the actual code to tweet images exists. First we retrieve the temporary access token from cookies and we exchange them with correct access token.

$token = $_COOKIE['Temp_Token'];
$secret = $_COOKIE['Temp_Secret'];
$img = $_COOKIE['Img_Url'];
$txt = $_COOKIE['Tweet_Txt'];
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => API_KEY,
'consumer_secret' => API_SEC,
'user_token' => $token,
'user_secret' => $secret, 
'curl_ssl_verifypeer' => false
 ));
$tmhOAuth->request("POST", $tmhOAuth->url("oauth/access_token", ""), array( 
 // pass the oauth_verifier received from Twitter 
 'oauth_verifier' => $_GET["oauth_verifier"] 
 )); 
 $response = $tmhOAuth->extract_params($tmhOAuth->response["response"]);
 $tmhOAuth->config["user_token"] = $response['oauth_token']; 
 $tmhOAuth->config["user_secret"] = $response['oauth_token_secret'];

6. After we get the correct access token, we tweet the image we want.

$img = './'.$img;
$code = $tmhOAuth->request('POST', 'https://api.twitter.com/1.1/statuses/update_with_media.json',
 array(
 'media[]' => "@{$img}",
 'status' => "$txt" 
 ),
 true, // use auth
 true // multipart
 );

7. The returned code from twitter API will tell us if the operation was done correctly or not.

if ($code == 200){
 echo '<h1>Your image tweet has been sent successfully</h1>';
 }else{
 tmhUtilities::pr($tmhOAuth->response['response']);
 }

Hopefully you find this simple tutorial for tweet images and twitter API helpful. Please share with us your feedback and comment using the comment box below. Also the full code is ready to download using the link Tweet Image Simple Tutorial Code

Like how we think? Lets Collaborate!