How to post tweet on Twitter with PHP
Php 19-Nov-2016

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.

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.