February 13, 2024 5:03 am

How to post tweet on Twitter with PHP

Twitter is one of the most famous micro blogging social site where you can explain your thoughts in 140 letters and today I am going to write an article on how to post a tweet on Twitter with PHP and this is a very simple procedure we already post an article on Twitter oAuth login and this will be supplement of that I hope you guys took benefit from it specially for fresh web Developers can learn more.

post-tweets-on-twitter-with-php

[wpdm_file id=54]DEMO

In this tutorial files included as below:

Contains two folders called oAuth and images with PHP files.

oauth
– twitteroauth.php //Functions to call for actions.
– OAuth.php // Twitter OAUTH library
images
– callback.php //Call back page create permanent credentials
– config.php // Configuration
– destroysessions.php // Erase all old sessions
– index.php // Main index file show data

To post tweets on Twitter you have to create an App click here

PHP Code to operate all the actions.

config.php

Contains your CONSUMER_KEY and CONSUMER_SECRET which you got when register application.

<?php
define('CONSUMER_KEY', 'CONSUMER_KEY');
define('CONSUMER_SECRET', 'CONSUMER_SECRET');
define('OAUTH_CALLBACK', 'OAUTH_CALLBACK');
?>

You have to modify this file and add your API credentials and call back url.

index.php

Contains PHP code to show sign in with Twitter image and redirect to twitter for authenticate and on redirect show text box to update tweet.

<?php
session_start();
require_once('oauth/twitteroauth.php');
require_once('config.php');
if(isset($_POST["status"]))
{
    $status = $_POST["status"];
    if(strlen($status)>=140)
    {
            $status = substr($status,0,139);
    }
    $access_token = $_SESSION['access_token'];
    $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);

    $connection->post('statuses/update', array('status' => "$status"));
    $message = "Tweeted Sucessfully!!";
}
if(isset($_GET["redirect"]))
{
    $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);

    $request_token = $connection->getRequestToken(OAUTH_CALLBACK);

    $_SESSION['oauth_token'] = $token = $request_token['oauth_token'];
    $_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];

    switch ($connection->http_code) {
      case 200:
        $url = $connection->getAuthorizeURL($token);
        header('Location: ' . $url); 
        break;
      default:
        echo 'Could not connect to Twitter. Refresh the page or try again later.';
    }
    exit;
}
if (empty($_SESSION['access_token']) || empty($_SESSION['access_token']['oauth_token']) || empty($_SESSION['access_token']['oauth_token_secret'])) {

    echo '<a href="./index.php?redirect=true"><img src="./images/lighter.png" alt="Sign in with Twitter"/></a>';
}
else
{
    echo "<a href='destroysessions.php'>Logout</a><br>";
    echo '<style>
    #status
    {
        width: 357px;
        height: 28px;
        font-size: 15px;
    }
    </style>
    <br>'.$message.'<br>
    <form action="index.php" method="post">
        <input type="text" name="status" id="status" placeholder="Write a comment....">
        <input type="submit" value="Post On My Wall!" style="padding: 5px;">
    </form>';
}
?>

When you loggedin it will store your access_token and oauth_token in session and use it till you destroy it.

if(strlen($status)>=140) used to check length of your message because twitter accept only 140 letters in a single tweet.

$url = $connection->getAuthorizeURL($token); Get authentication url and redirect to the twitter for permission.

callback.php

Contain PHP code to verify authentication and create sessions of token and redirect to index.php file where you can see text box to add tweet and post it to your twitter.

<?php
session_start();
require_once('oauth/twitteroauth.php');
require_once('config.php');

if (isset($_REQUEST['oauth_token']) && $_SESSION['oauth_token'] !== $_REQUEST['oauth_token']) {
  $_SESSION['oauth_status'] = 'oldtoken';
  header('Location: ./destroysessions.php');
}

$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);

$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
//save new access tocken array in session
$_SESSION['access_token'] = $access_token;

unset($_SESSION['oauth_token']);
unset($_SESSION['oauth_token_secret']);

if (200 == $connection->http_code) {
  $_SESSION['status'] = 'verified';
  header('Location: ./index.php');
} else {
  header('Location: ./destroysessions.php');
}

destroysessions.php

Contain PHP code used to destroy session and redirect to index.php for fresh login.

Feedback

We are looking forward for your feedback and comments, also added a demo for this and source code to download hope you like it.

Author Huzoor Bux

I am Huzoor Bux from Karachi (Pakistan). I have been working as a PHP Developer from last 5+ years, and its my passion to learn new things and implement them as a practice. Basically I am a PHP developer but now days exploring more in HTML5, CSS and jQuery libraries.


Tutorial Categories:

16 responses to “How to post tweet on Twitter with PHP”

  1. fjvalencian says:

    Hi, i am trying to run this code in my server, is this correct?

    Thanks for your help.

  2. gomathy says:

    Thanks for coding its working! i want to get user name, id and mail id through this login. How can i get user details?

  3. gomathy says:

    Thanks for coding its working! i want to get user name, id and mail id through this login. How can i get user details?

  4. Sean says:

    I am getting Warning: Cannot modify header information – headers already sent by (output started at /home/seanbfep/public_html/testing/twitter/index.php:24) in /home/seanbfep/public_html/testing/twitter/index.php on line 52, idk what i am doing wrong

  5. Usama says:

    I want to know If i have saved the auth_code and secret value in DB . Now after few days i triger an event to post a tweet for the user for which i have already auth tokens.

    Best Regards

  6. Mark Bagnall says:

    When sharing URL, its not turning into a link on the tweet

  7. priyanka patodia says:

    this demo working fine. but when uploading the same on my server it is not working… pls help … urgent

  8. usama feroz says:

    I was developing an application for my currently running website I was not successful to send a tweet for a user who I have already authenticated.

    I want to send a tweet on user account when he comes to my website and have some activity. I have stored customer key and customer secret in database. first time (when the user is authenticated) it runs ok but after words it donot works any more. and send me authentication error.

    do you have any solution?

    Best regards

  9. sreenu says:

    Hi where i want to place oauth_access_token in that file

Leave a Reply

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