• Main Menu
  • 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.

    Got Something To Say:

    Your email address will not be published. Required fields are marked *

    42 comments
    1. Shital Pimpale

      11 May, 2016 at 6:43 am

      worked for me.thank you.but need to post image also,i don’t know to to do it.

      Reply
    2. Tormy Van Cool

      7 October, 2015 at 4:50 pm

      your code doesn’t exist anylonger

      Reply
    3. dejansoftware

      14 February, 2015 at 2:50 pm

      hi,

      I would like to send 96 tweets per day, that is 1 tweet every 15 min from preprared txt file (one line is one tweet)

      Is this possible with this method?

      Thanks

      Reply
    4. cyberfunk77

      6 February, 2015 at 2:46 pm

      Hello and thanks for this tutorial. I followed your instructions but I get “Fatal error: Class ‘TwitterOAuth’ not found…” when trying to execute the php tweet. Any help is much appreciated. All files are in the same directory on my server.

      Reply
    5. Vemuez

      3 January, 2015 at 6:38 pm

      After many errors and trials, i have finally managed to get it working BUT it doesn’t appear even after changing the read-write permission, updating the access token key to apply these changes and etc. It just doesn’t want to appear? Know where the problem may lie?

      Reply
    6. saif el din hesham

      25 December, 2014 at 7:07 pm

      it worked but i can’t see the tweet, i’m working with xamp(php my admin) any help ?

      Reply
    7. Ivano De Luca

      19 November, 2014 at 9:44 pm

      Does not work. What is the matter? I made all, but i have no tweet… and no error messages. How could I do to understand the problem?

      Reply
      • JorgeT

        24 November, 2014 at 2:32 am

        I had a similar problem. Not enough to change the permissions to Read -Write for personal credentials remain Read. Create a new Twitter application from the start with Read -Write , because these permissions to personal credentials and through these new credentials are inherited apply the process. So the process work well for me.

        Reply
    8. Taani

      23 September, 2014 at 7:12 am

      It is brilliant, neat, clean and short code and worked like a charm.
      What I want to ask that is there any limitation of posting tweets per minute / per hour or is it simply unlimited?
      Best of Luck

      Reply
    9. Niksilp

      1 September, 2014 at 9:04 am

      I can’t get this code to work and I’m not sure why. 🙁 My app is set to read/write, I generated my access tokens after setting it as such (and have even tried re-generating the tokens a few times since then). I have the latest twitteroauth.php from Abraham at GitHub… His has ssl_verifypeer = FALSE; but I’ve tried with it set to TRUE as well.

      I also tried copying and pasting the changes listed exactly from this article ($connection->$host = “https://api.twitter.com/1.1/”; $connection->ssl_verifypeer = TRUE;) but that returns a PHP error (” Parse error: syntax error, unexpected T_OBJECT_OPERATOR, expecting ‘,’ or ‘;’ in … line 21 ” — line 21 is ” public $connection->$host = “https://api.twitter.com/1.1/”; “).

      I tried searching around for some other PHP code to achieve the same end as what’s been provided here, but everything else I’ve tried I encountered ” {“errors”:[{“message”:”Could not authenticate you”,”code”:32}]} “. I can’t even get the code provided here at Tech FAQ to give me an error, so I’m not sure if I’m running into the same issue; I just get a blank page when I try to access the index.php and nothing ever gets posted to my account.

      Any help would be much appreciated. I’m really stuck and quite disappointed… This seems like such a simple thing and it’s so perfect for what I need. I just don’t have enough knowledge on PHP and Twitter API to troubleshoot it myself.

      Reply
    10. leobiscuits

      30 July, 2014 at 1:29 pm

      Hey!

      Great tutorial, works like a charm!
      Just one question though, Is there a way to set the tweet to appear on a specific date, like an hour after the user used the API? Thanks!

      Reply
    11. neveroffguard

      2 April, 2014 at 7:49 am

      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.

      Reply
    12. gilbnet

      15 December, 2013 at 2:51 am

      my app no tweet 🙁 return true ???

      Reply
    13. Elroy Paisley

      23 September, 2013 at 5:52 pm

      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!!

      Reply
      • WillSpencer

        24 September, 2013 at 9:55 am

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

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

        Reply
        • Elroy Paisley

          24 September, 2013 at 10:01 am

          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!

          Reply
          • WillSpencer

            24 September, 2013 at 10:03 am

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

            Reply
            • Elroy Paisley

              24 September, 2013 at 2:52 pm

              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.

            • Elroy Paisley

              24 September, 2013 at 8:17 pm

              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

          24 September, 2013 at 10:04 am

          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)
          }
          }
          }

          Reply
    14. Alan Marcel

      25 August, 2013 at 3:12 am

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

      Reply
    15. Nazar

      3 July, 2013 at 10:55 pm

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

      No idea what the error means 😐

      Reply
    16. bob

      7 June, 2013 at 8:45 pm

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

      Reply
      • WillSpencer

        9 June, 2013 at 4:22 am

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

        Reply
    17. Meenu

      1 May, 2013 at 3:33 pm

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

      Reply
      • Abdulqader Kapadia

        3 May, 2013 at 3:10 am

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

        Reply
    18. JDR

      22 April, 2013 at 11:48 pm

      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

      Reply
    19. Neeraj

      12 April, 2013 at 8:14 pm

      Well done guys

      Reply
    20. Mushtaq

      27 March, 2013 at 4:02 pm

      brilliant guys my best wishes with u guys keep rocking

      may god help u guys to help others

      Reply
    21. Mushtaq

      27 March, 2013 at 4:00 pm

      thanks a million man you rock man really

      Reply
    22. Jason

      19 March, 2013 at 1:01 pm

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

      Reply
      • Abdulqader Kapadia

        25 March, 2013 at 1:39 am

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

        Reply
    23. Ivan van Oosterhout

      10 March, 2013 at 11:56 pm

      I get this error???

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

      Reply
      • Abdulqader Kapadia

        11 March, 2013 at 2:32 am

        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.

        Reply
    24. Abrahim Vos

      4 March, 2013 at 9:58 pm

      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…

      Reply
    25. Abdulqader Kapadia

      4 March, 2013 at 12:38 pm

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

      Reply
    26. Mattias

      4 March, 2013 at 8:53 am

      Great artcile! However, I’d like the same script to post it on the users own Twitter account. Like Dropbox referral: https://www.dropbox.com/referrals. How to? 🙂

      Reply
    27. WillSpencer

      18 February, 2013 at 7:16 am

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

      Reply
      • sujit

        22 February, 2015 at 1:54 pm

        hey what you did its not working for me although i regenerated after read write permission please help

        Reply
    Programming
    } 427 queries in 0.485 seconds.