Twitter API with PHP! How to Tweet!



In this post we learn how to use the Twitter API for posting and retrieving tweets from twitter. We also learn how to setup a Twitter App so we can get the right credentials for making our POST and GET requests.

Step 1: Create a Twitter App

In order to connect to the API with a script, we need some credentials so we can authenticate with Twitter. To get these credentials we need to setup a Twitter App.

  1. Go to https://developer.twitter.com/en/apps and click on the “create an app” button. To create an App, you need to be setup with a developer account. If you do not have a developer account, Twitter will send you to a form which will set you up with a developer account. Then you can come back here and try creating an app again.
  2. Fill out the create app form, create the app, and the page should  refresh.
  3. Click on the “Keys and Tokens” tab. This tab contains the credentials required in our code in order to make a successful request to the Twitter API. twitter app

 

Step 2: Get the twitter-api-php Wrapper

This wrapper will help us out by doing much of he heavy lifting for us. All we have to do to create a Twitter object is instantiate it and pass along our credentials from Step 1. From there, we can hit the endpoints by using the Twitter object and passing along the necessary parameters.

Download the wrapper from GitHub https://github.com/J7mbo/twitter-api-php

 

Step 3: Create our Scripts!

Now that we have our credentials and our TwitterAPIExchange.php wrapper, we are all set to post a tweet, and get a list of our tweets.

tweet.php

This script will post a tweet to our Twitter timeline. We include the Twitter wrapper, our credentials, pass along our tweet to the correct endpoint, and our tweet gets posted to Twitter.

Twitter API Docs for posting  a tweet https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update

// include config and twitter api wrappe
require_once( 'config.php' );
require_once( 'TwitterAPIExchange.php' );

// settings for twitter api connection
$settings = array(
    'oauth_access_token' => TWITTER_ACCESS_TOKEN, 
    'oauth_access_token_secret' => TWITTER_ACCESS_TOKEN_SECRET, 
    'consumer_key' => TWITTER_CONSUMER_KEY, 
    'consumer_secret' => TWITTER_CONSUMER_SECRET
);

// twitter api endpoint
$url = 'https://api.twitter.com/1.1/statuses/update.json';
	
// twitter api endpoint request type
$requestMethod = 'POST';

// twitter api endpoint data
$apiData = array(
    'status' => 'This tweet is comming from an awesome script written using php and the Twitter API! #Geek #PHP #TwitterAPI',
);

// create new twitter for api communication
$twitter = new TwitterAPIExchange( $settings );

// make our api call to twiiter
$twitter->buildOauth( $url, $requestMethod );
$twitter->setPostfields( $apiData );
$response = $twitter->performRequest( true, array( CURLOPT_SSL_VERIFYHOST => 0, CURLOPT_SSL_VERIFYPEER => 0 ) );

// display response from twitter
echo '<pre>';
print_r( json_decode( $response, true ) );

Running this script will post a tweet to our Twitter timeline and display the response we get back from Twitter in the browser. In this case, Twitter will give us back a response containing the tweet we just posted. Double check the tweet was posted to Twitter!

tweet

get_tweets.php

In this script we will be getting our most recent tweet and displaying it out in the browser. The parameters to pass along to this endpoint are the screen_name, and the count. The screen_name is our twitter handle, the count is how many tweets we want to get back. For getting only our most recent tweet, I am passing along a count of 1 to the user_timeline endpoint. This is the endpoint for getting tweets for a user.

Twitter API Docs for getting tweets https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline

// include config and twitter api wrappe
require_once( 'config.php' );
require_once( 'TwitterAPIExchange.php' );

// settings for twitter api connection
$settings = array(
    'oauth_access_token' => TWITTER_ACCESS_TOKEN, 
    'oauth_access_token_secret' => TWITTER_ACCESS_TOKEN_SECRET, 
    'consumer_key' => TWITTER_CONSUMER_KEY, 
    'consumer_secret' => TWITTER_CONSUMER_SECRET
);

// twitter api endpoint
$url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
	
// twitter api endpoint request type
$requestMethod = 'GET';

// twitter api endpoint data
$getfield = '?screen_name=justin_stolpe&count=1';

// make our api call to twiiter
$twitter = new TwitterAPIExchange( $settings );
$twitter->setGetfield( $getfield );
$twitter->buildOauth( $url, $requestMethod );
$response = $twitter->performRequest( true, array( CURLOPT_SSL_VERIFYHOST => 0, CURLOPT_SSL_VERIFYPEER => 0 ) );
$tweets = json_decode( $response, true );
    
// display all info we got back from twitter
//echo '<pre>';
//print_r( $tweets );
?>
<h1>Latest Tweet</h1>
<?php foreach ( $tweets as $tweet ) : ?>
    <img src="<?php echo $tweet['user']['profile_image_url']; ?>" />
    <a href="https://twitter.com/<?php echo $tweet['user']['screen_name']; ?>" target="_blank">
        <b>@<?php echo $tweet['user']['screen_name']; ?></b>
    </a> tweeted:
    <br />
    <br />
    <?php echo $tweet['text']; ?>
    <br />
    <br />
    Tweeted on <?php echo $tweet['created_at']; ?>
    <br />
    <hr />
<?php endforeach; ?>

Running the get_tweets.php will display our most recent post in the browser like shown in this image.

get tweet

Links

YouTube Video

Code on GitHub

Live Demo

The full code example can be found in the GitHub link above along with a live demo displaying my most recent tweet! The video tutorial for this can also be found in the YouTube link above. That is going to do it for this post! Leave any comments/questions/concerns below and thanks for stopping by the blog!

 

3 comments

  1. Hi, I use your script but I get a Twitter API error; N° 32. Could you explain how to fix following bug ?
    Cordially,
    Ridvan

    Array
    (
    [errors] => Array
    (
    [0] => Array
    (
    [code] => 32
    [message] => Could not authenticate you.
    )

    )

    )

Leave a Reply to justinstolpe Cancel reply

Your email address will not be published. Required fields are marked *