Search the blog

I recently had to post new tweets to Twitter via PHP using V2 of their API but couldn’t find any decent examples online that didn’t use V1 or V1.1. I eventually figured it out using the great package TwitterOAuth.

Install this package via composer require abraham/twitteroauth first (or manually) and visit developer.twitter.com, create a new app to get the credentials needed to use the API (see below). Then you can post a tweet based off of the code below.

use Abraham\TwitterOAuth\TwitterOAuth;

// Connect
$connection = new TwitterOAuth($twitterConsumerKey,             // Your API key
                               $twitterConsumerSecret,          // Your API secret key
                               $twitterOauthAccessToken,        // From your app created at https://developer.twitter.com/
                               $twitterOauthAccessTokenSecret); // From your app created at https://developer.twitter.com/

// Set API version to 2                           
$connection->setApiVersion('2');

// POST the tweet; the third parameter must be set to true so it is sent as JSON
// See https://developer.twitter.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/post-tweets for all options
$response = $connection->post('tweets', ['text' => 'Hello Twitter'], true);

if (isset($response['title']) && $response['title'] == 'Unauthorized') {

    // Handle error

} else {

	var_dump($response);

	/*
	object(stdClass)#404 (1) {
	  ["data"]=>
	  object(stdClass)#397 (2) {
	    ["id"]=>
	    string(19) "0123456789012345678"
	    ["text"]=>
	    string(13) "Hello Twitter"
	  }
	}
	*/

}
Tim Bennett is a freelance web designer from Leeds. He has a First Class Honours degree in Computing from Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.