Tweet an Image to Twitter using PHP
Twitter remains one of the most popular social media platforms for sharing thoughts, media, and updates. Automating tweets can be a powerful tool for developers managing content-driven websites or applications. This guide demonstrates how to tweet an image using PHP, leveraging the Twitter API.
This tutorial is actually the second part of our previous tutorial : https://youthsforum.com/2024/12/post-tweet-to-twitter-using-php/
In previous tutorial, we actually tweet normal text. Now we are going to tweet an image.
Prerequisites
Before getting started, ensure you have:
- Twitter Developer Account: Create a Twitter Developer account and set up a project to obtain API credentials.
- Composer Installed: Use Composer to manage dependencies.
- Abraham’s TwitterOAuth Library: Install it using command : composer require abraham/twitteroauth
Full Source Code
<?php require 'vendor/autoload.php'; use Abraham\TwitterOAuth\TwitterOAuth; $credentials = json_decode(file_get_contents('credentials.json')); $connection = new TwitterOAuth( $credentials->api_key, $credentials->api_secret, $credentials->access_token, $credentials->access_token_secret ); $connection->setApiVersion('1.1'); $imagePath = realpath('image.jpg'); $image = $connection->upload('media/upload',['media'=>$imagePath]); $tweet['text'] = "Silence Speaks more than Words"; $tweet['media']['media_ids'][] = $image->media_id_string; $connection->setApiVersion('2'); $response = $connection->post('tweets', $tweet); if(isset($response->data->id)){ echo "Tweeted successfully"; } else{ echo "Tweet Failed Error: ".$response->detail; }
Follow this video for complete guidance: