Send Tweets to your Twitter Account via PHP

Posting status messages to a Twitter account via PHP is quite useful in many scenarios. Like automatically tweeting your blog’s latest content, tweeting list of facts, tips or quotes at regular intervals, tweeting daily news, etc. This article’s intention is to show how you can send a tweet to your Twitter account via PHP programming.

Required APIs, Tokens and Files

We will require the following things in order to tweet via PHP.

  1. An app created via your Twitter account with Read/Write permission.
  2. Consumer Key, Consumer Secret, Access Token, Access Token Secret
  3. OAuth API (i.e. a file called OAuth.php)
  4. PHP Library to support OAuth for Twitter’s REST API (i.e. a file called twitteroauth.php)

Let’s get started by following the below steps carefully.

Step 1: Go to the Create New App screen and login with your Twitter account.

Step 2: On the Create an application screen, enter the required details like Name, Description, and Website for your new Twitter app. Callback URL isn’t necessary and you may leave it blank. Accept the Developer Rules of the Road agreement. Enter the captcha and click Create your Twitter application.

Create-an-application-screen-at-Twitter

Step 3: If your Twitter app is created successfully, you will see the app screen. On this screen under the OAuth Settings section, copy+paste the Consumer Key and Consumer Secret in a text editor for future reference.

Clicking the Create my access token will be of no use at the moment, since the Access Level is still Read-Only. We need it to be with Read-Write permissions.

Step 4: Go to the Settings tab. Under the Application Type section, select Read and Write or Read, Write and Access direct messages if your application requires access to Direct Messages too. Click the Update this Twitter application’s settings button.

Twitter-app-Read-and-Write-Permissions

Step 5: Now, go back to the Details tab. You should see Access Level changed to Read and Write under the OAuth Settings section.

Under the Your access token section, click Create my access token button. If successful, you will see newly generated Access Token and Access Token Secret under the OAuth Tool tab. Copy ‘Access Token’ and ‘Access Token Secret’ in a text editor for future reference.

Step 6: Download the OAuth.php and twitteroauth.php files and place them in a directory on your server (say under domainname.com/mytwitterbot). Both of these files should be at the same directory level.

IMPORTANT: Twitter retired the API v1 version on June 11, 2013. We now have to use Twitter’s API v1.1 version. Therefore, we need to make some changes in the twitteroauth.php file.

Open twitteroauth.php in a code editor to modify the host and ssl_verifypeer values. Make the changes as follows:

$connection->$host = "https://api.twitter.com/1.1/";
$connection->ssl_verifypeer = TRUE;

Step 7: Create a new file called index.php and add the following code to it.

<?php

// Include twitteroauth
require_once('twitteroauth.php');

// Set keys
$consumerKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX';
$consumerSecret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX';
$accessToken = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX';
$accessTokenSecret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX';

// Create object
$tweet = new TwitterOAuth($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);

// Set status message
$tweetMessage = 'This is a tweet to my Twitter account via PHP.';

// Check for 140 characters
if(strlen($tweetMessage) <= 140)
{
    // Post the status message
    $tweet->post('statuses/update', array('status' => $tweetMessage));
}

?>

What the code does: This code includes the twitteroauth.php file which already includes the OAuth.php file. Define variables for Consumer Key, Consumer Secret, Access Token, Access Token Secret and copy the respective keys. Create an object of the class TwitterOAuth by passing the keys as parameters. Define a variable which holds the actual status message to be tweeted to your Twitter account. Before posting, it’s safer to check the length of the status message to be below 140 characters – else, the code may show an error. Call the post function as shown with your status message.

Place index.php too in the same directory, i.e. domainname.com/mytwitterbot.

Now, open the URL in your browser. In our case, it would be like http://domainname.com/mytwitterbot. In few seconds, you should see a tweet update in your Twitter account with the set status message.

The status message can be populated from an array, XML file, plain text file, database, or from another API.

Automate Tweets in PHP via CRON
To schedule an auto-tweeting functionality at regular intervals, you can add the above created index.php file to your CRON jobs. This way, the tweet will automatically go to your Twitter account at set intervals.

Did you face any problem while implementing the above method? Please share your experience in the comments below.

Rate this article:

Last updated .

Follow Abdulqader Kapadia on
  • Utpal

    Hello, I have made the same thing what you have said but when running the file then nothing happening and also the tweet message is not appearing on my twitter account. Please help me how can i solve the issue.

    Thanks,

    • WillSpencer

      Utpal, try recreating your Access Token and Access Token Secret after setting your Access Level changed to Read and Write.

      • Utpal

        thanks for your reply. It’s working fine now. thanks again

  • Utpal

    Hello, I have one another question regarding direct message on twitter. Do you have any example code of how can i send direct message to multiple twitter account.

    Thanks,

  • Abdulqader Kapadia

    Mattias, I didn’t really understand your question. Can you please elaborate?

  • http://www.facebook.com/jahrvos Abrahim Vos

    Great script sofar, thanks, works like charm. Next step I don’t really understand. How to get the status message into a variable.
    And further: how to include an image. I tried it with adding the URL of the image in the message but that doesn’t seem to work…

  • Ivan van Oosterhout

    I get this error???

    Fatal error: Cannot redeclare class OAuthException in /home/deb00000/domains/website.com/public_html/testtwit/OAuth.php on line 8

    • Abdulqader Kapadia

      This could be the result of declaring/including “twitteroauth.php” multiple times. I recommend you follow the above steps from scratch in a fresh directory.

  • Jason

    Worked exactly as you said it would first time. THANKS!!! for this great walk-though

    • Abdulqader Kapadia

      Jason, thank you. We are glad it helped you.

  • Mushtaq

    thanks a million man you rock man really

  • Mushtaq

    brilliant guys my best wishes with u guys keep rocking

    may god help u guys to help others

  • Neeraj

    Well done guys

  • JDR

    Getting an error:

    Warning: require_once(twitteroauth.php) [function.require-once]: failed to open stream: No such file or directory in /homepages/20/d98661292/htdocs/mro/twitterbot/index.php on line 4

    Fatal error: require_once() [function.require]: Failed opening required ‘twitteroauth.php’ (include_path=’.:/usr/lib/php5′) in /homepages/20/d98661292/htdocs/mro/twitterbot/index.php on line 4

    I’m a total php noob so forgive me if this is something obvious

  • http://www.facebook.com/ahmed.5.hisham Ahmed Hisham

    Many thanks for the tutorial…

  • Meenu

    Hey Very nicely explained.. but ca u please tell me how to send tweets via xml file

    • Abdulqader Kapadia

      You will need to implement XML logic to read from an XML file, where it says “Set status message” in the code.

  • bob

    Fatal error: Class ‘TwitterOAuth’ not found in /opt/lampp/htdocs/testtwitter.php on line 15

    • WillSpencer

      Bob, it seems like you’re missing twitteroauth.php.

  • Nazar

    ( ! ) Fatal error: Call to undefined function curl_init() in D:ApplicationswampwwwBSHtwittertwittertwitteroauth.php on line 195

    No idea what the error means :|

  • Alan Marcel

    very nice tutorial. It worked on the first try! thank you a lot!

  • Elroy Paisley

    This is terrific, took some tinkering but I get it working. Could I ask how I could use this code to RETWEET, rather than tweet. For example, if I have a tweet ID# and I would like to retweet it, how would I alter this (great) code to make that happen? thanks!!

    • WillSpencer

      Here’s the code I’m using to retweet:

      $status = $twitter_connection->post( ‘statuses/retweet/’ . $retweet, array( ‘id’ => $retweet ) );

      • Elroy Paisley

        I see you’re using $twitter_connection but wouldn’t you want to use $tweet per the code above? Just checking. Thanks for the reply!

        • WillSpencer

          The variable names are different in my current code than in the code above. :D

          • Elroy Paisley

            Hi Will, thanks for your feedback. Any chance you can help me diagnose my “Sorry, page does not exist” problem? I’ve checked the tweetID (and changed it repeatedly to other tweets) and I’ve checked my tokens/keys.

          • WillSpencer

            I can’t see why you’re getting that error.

            Perhaps review this?

            https://dev.twitter.com/docs/api/1.1/post/statuses/retweet/:id

          • Elroy Paisley

            Yeah I’ve looked through that, no idea what’s wrong. Going to start from scratch on the retweeting. But thanks so much for your time!

          • Elroy Paisley

            Happy ending, The final bit of reweet code looks like this:

            $retweetResult = $tweet->post(‘statuses/retweet/’.$postID);

            it works well. now to figure out the syntax for favorites!

      • Elroy Paisley

        Hmmm. Seems like no matter what I set $retweet to be (no matter the tweet ID) I get this:

        object(stdClass)#5 (1) {
        ["errors"]=>
        array(1) {
        [0]=>
        object(stdClass)#6 (2) {
        ["message"]=>
        string(31) “Sorry, that page does not exist”
        ["code"]=>
        int(34)
        }
        }
        }

  • gilbnet

    my app no tweet :( return true ???

  • http://salvatorecapolupo.it/ Salvatore Capolupo

    This is not workign for me, I got some problem using cron-job for Tweets, maybe it should depend from Oauth Read/write grants?

  • neveroffguard

    Hi,
    Thank you for this tutorial.

    I am using XAMPP and facing the below error Fatal error: Class ‘OAuthSignatureMethod_HMAC_SHA1′ not found in C:xampphtdocs.