Do you want to send a Tweet on Twitter with PHP? You might be building an application where you need to programmatically post a Tweet on your Twitter account. It can be achieved using Twitter’s REST API. In this article, we’ll study sending a Tweet on Twitter using Twitter API and PHP.
I’ll use the TwitterOAuth library for the integration of Twitter API. This is an open-source package that allows seamless interaction with Twitter’s REST API.
With the help of this library, I’m going to write code for
- Posting a Tweet on Twitter
- Posting a Tweet on Twitter along with images
Now to get started, you first require to register the application on the Twitter Developer Account. Upon creating an application, you’ll get the API credentials that will be used in our PHP code. These API credentials will act as an identifier of your account.
Register Twitter Application
To register an application, go to the Twitter Developer website and follow the below steps.
- Sign up for a Twitter developer account.
- Create a Twitter App within a developer portal.
- Complete the steps as prompted.
- Copy your Consumer Keys, Access Token, and Secret.
Installation of TwitterOAuth Library
You are ready with the API keys of your Twitter account. Next, install the TwitterOAuth library.
To install this package you should have Composer installed on your system. Also, make sure the cURL extension is enabled on your server.
Open the command prompt in the project root directory and run the command:
composer require abraham/twitteroauth
After installing the library, you have to include the package’s environment and also define API keys using PHP constant. Refer to the below code and add it to your PHP file.
<?php
require_once "vendor/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
define('CONSUMER_KEY', 'ENTER_YOUR_CONSUMER_KEY');
define('CONSUMER_SECRET', 'ENTER_YOUR_CONSUMER_SECRET');
define('ACCESS_TOKEN', 'ENTER_YOUR_ACCESS_TOKEN');
define('ACCESS_TOKEN_SECRET', 'ENTER_YOUR_ACCESS_TOKEN_SECRET');
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
Make sure you have replaced all placeholders with their actual values.
Send a Tweet on Twitter with PHP
Twitter provides REST APIs for developers so they can interact with Twitter from their own applications. In order to use these APIs, you need to send HTTP requests to the API endpoints with the required parameters.
For example, posting a Tweet requires you to hit the TWITTER_API_URL/statuses/update
endpoint. Don’t worry about the base URL(TWITTER_API_URL) of an API endpoint. The TwitterOAuth library will handle it for you.
Having said that, let’s write the code for it. From the package, you’ll find below 2 lines that will be enough to post a simple text tweet.
$status = 'This is a test tweet. https://artisansweb.net';
$result = $connection->post("statuses/update", ["status" => $status]);
Here, we hit the API endpoint called statuses/update
given by Twitter. This endpoint is used to send Tweets on your Twitter account.
If for some reason your Tweet is not posting then you can print the error received in a response. This error will help you to debug the issue.
if ($connection->getLastHttpCode() == 200) {
echo "Your Tweet posted successfully.";
} else {
echo 'error: ' . $result->errors[0]->message;
}
So our final code is as follows.
<?php
require_once "vendor/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
define('CONSUMER_KEY', 'ENTER_YOUR_CONSUMER_KEY');
define('CONSUMER_SECRET', 'ENTER_YOUR_CONSUMER_SECRET');
define('ACCESS_TOKEN', 'ENTER_YOUR_ACCESS_TOKEN');
define('ACCESS_TOKEN_SECRET', 'ENTER_YOUR_ACCESS_TOKEN_SECRET');
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
$status = 'This is a test tweet. https://artisansweb.net';
$result = $connection->post("statuses/update", ["status" => $status]);
if ($connection->getLastHttpCode() == 200) {
echo "Your Tweet posted successfully.";
} else {
echo 'error: ' . $result->errors[0]->message;
}
Post a Tweet with Media
If you are looking to send images into your Tweet, you can do it using the same statuses/update
endpoint. All you need to do is pass a few extra parameters of your media.
You have to first upload media via Twitter API which in return will give the media id. This media id should be sent as an additional parameter.
I assume you have a 1.jpg
file in the directory. Adjust this image path as per your flow.
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
$media = $connection->upload('media/upload', ['media' => getcwd(). '/1.jpg']);
$parameters = [
'status' => 'Testing Media Upload via API',
'media_ids' => $media->media_id_string
];
$result = $connection->post('statuses/update', $parameters);
if ($connection->getLastHttpCode() == 200) {
echo "Your Tweet posted successfully.";
} else {
echo 'error: ' . $result->errors[0]->message;
}
You can also send multiple images in your Tweet by generating multiple media ids.
$media1 = $connection->upload('media/upload', ['media' => getcwd(). '/1.jpg']);
$media2 = $connection->upload('media/upload', ['media' => getcwd(). '/2.jpg']);
$parameters = [
'status' => 'Testing Media Upload via API',
'media_ids' => implode(',', [$media1->media_id_string, $media2->media_id_string])
];
I hope you understand how to post a Tweet on Twitter with PHP. This tutorial should help you to easily integrate Twitter API into your website. Please share your thoughts and suggestions in the comment section below.
Related Articles
- Twitter OAuth Login in Website with PHP
- How to Use Twitter Search API
- How to Create Twitter Feed Widget for Website
If you liked this article, then please subscribe to our YouTube Channel for video tutorials.
The code is no longer functional.
You must declare the version of the API and change it to the current one depending on the method to be called. here is the fix:
$image = [];
$connection->setApiVersion(‘1.1’);
$media = $connection->upload(‘media/upload’, [‘media’ => ‘./image.jpg’]);
array_push($image, $media->media_id_string);
$data = [
‘text’ => ‘Hello world’,
‘media’=> [‘media_ids’ => $image]
];
$connection->setApiVersion(‘2’);
$content = $connection->post(“tweets”, $data, true);
Hey,
Not working with this method, because I am trying to create just a post on Twitter my account but giving this issue please help.
+”message”: “You currently have access to a subset of Twitter API v2 endpoints and limited v1.1 endpoints (e.g. media post, OAuth) only. If you need access to this endpoint, you may need a different access level. You can learn more here: https://developer.twitter.com/en/portal/product”
+”code”: 453
Hello there!
Is there any way to schedule posts to be published in the future?
Thanks for your insight!
Rosamunda
Buenos Aires – Argentina
It’s not possible at the API end. You have to apply some logic like Cron, the scheduled date in the database, etc.
Thanks for your kind reply Sajid!
not worked with message:
error: You currently have Essential access which includes access to Twitter API v2 endpoints only. If you need access to this endpoint, you’ll need to apply for Elevated access via the Developer Portal. You can learn more here: https://developer.twitter.com/en/docs/twitter-api/getting-started/about-twitter-api#v2-access-leve
You can use this
https://github.com/noweh/twitter-api-v2-php
Works like a charm.
Cool!
But what about tweet with media?
Any solutions?
This (at least the endpoint…) no longer seems to work
Thanks, how to catch error on this library ?
Using try/catch block.
try {
//actual code
} catch(Exception $e) {
echo $e->getMessage();
}
how to add new line in the post
Thanks so much!
I was looking around for a simple tutorial on how to send tweets. This one put me in the right direction in no time. I had my first test done in just under 15 minutes and it worked instantly.
Keep up the good work!