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, 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
                               $twitterOauthAccessTokenSecret); // From your app created at

// Set API version to 2                           

// POST the tweet; the third parameter must be set to true so it is sent as JSON
// See for all options
$response = $connection->post('tweets', ['text' => 'Hello Twitter'], true);

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

    // Handle error

} else {


	object(stdClass)#404 (1) {
	  object(stdClass)#397 (2) {
	    string(19) "0123456789012345678"
	    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.