Tweets with media file using Oauth API in php is simple and cute, It simply allow us to upload an media file to twitter and make a status with image is far better than old text only status message. Yes now I have a situation to post an image to twitter with status update so here I’m sharing what code is works fine for me. You can check my old post related to post to twitter using Oauth api for text only status updates
First of all using Oauth API with twitter is very simple and nice, Recently twitter changed their APP creation now you have to give your mobile number to create an APP with write permission. If you have already an app with write permission then that one’s credentials can be used for Tweets with media file.
For creating twitter Oauth API Apps check this link .
After creating your Apps on twitter account just create a PHP file or your custom function for post to twitter using Oauth API, this is using version 1.1.
<?PHP require_once 'twitteroauth.php'; define("CONSUMER_KEY", "****consumer key*******"); define("CONSUMER_SECRET", "*******Consumer secret********"); define("OAUTH_TOKEN", "**********Oauth token*******"); define("OAUTH_SECRET", "*****Oauth Secret********"); $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_SECRET); $content = $connection->get('account/verify_credentials'); $image = 'walkswithme.png'; $status_message = 'Attaching an image to a tweet'; $status = $connection->upload('statuses/update_with_media', array('status' => $status_message, 'media' => file_get_contents($image))); echo json_encode($status); ?>
Make sure few thing then your first attempt will work successfully.
- Your APP have proper read/write permission.
- Your APP Keys are correct in configuration file without white spaces.
- You didn’t touch any code on the API core files.
- The media attaching with the status message is valid format and it exists in the given path.
- Do not use status message and media file directly inside upload() It may not work.
Make sure your twitter apps have the proper access to read/write data from/to your twitter account.
This simple code will post an image with status message to my own twitter account like below.
You can download the working example from below link.