Twitter OAuth Status Update using PHP.
Wall Script
Wall Script
Monday, April 14, 2014

Twitter OAuth Status Update using PHP.

Twitter is the most powerful platform that you can express your thoughts with your followers. Few months back Twitter has been updated there OAuth APIs, this tutorial will explain three import systems like, login with Twitter, storing Twitter Oauth tokens into database and update Twitter status message with your own web application. This script helps you to share your web application updates with user Twitter status updates.

Twitter OAuth Status Update using PHP.


Download Script     Live Demo

Database
Sample database users table columns id, email, oauth_uid, oauth_provider and username.
CREATE TABLE  `TwitterUpdate` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`uname` varchar(50),
`name` varchar(90),
`oauth_token` varchar(90),
`oauth_token_secret` varchar(90),
PRIMARY KEY (`user_id`),
UNIQUE KEY `uname` (`uname`)
);

The tutorial contains three folders called facebook,twitter and config with PHP files.
EpiTwitter
-- TwitterConfig.php 
-- EpiTwitter.php
-- EpiCurl.php
-- EpiOAuth.php //Twitter Oauth Library
index.php
home.php
db.php
TwitterLogin.php
TwitterCallback.php
TwitterUpdate.php
TwitterLogout.php

Create Twitter Application
You have to create an application and give the details in the following way.
Twitter OAuth Status Update using PHP.

Application Setting
Modify application access level.
Twitter OAuth Status Update using PHP.

Access Level
Update Read only to Read and Write
Twitter OAuth Status Update using PHP.

Application API keys
https://apps.twitter.com/app/new
Twitter OAuth Status Update using PHP.

Twitter Application Setup
You have to modify application API key and Api secret.
TwitterConfig.php
<?php
$consumer_key = 'API key';
$consumer_secret = 'API secret';
?>

db.php
Database configuration file, update database details such as username, password and database name.
<?php
session_start();
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'databaseName');
$connection = @mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE) or die(mysqli_error());
?>

TwitterLogin.php
This code will generate Twitter authorization url.
<?php
include 'EpiTwitter/EpiCurl.php';
include 'EpiTwitter/EpiOAuth.php';
include 'EpiTwitter/EpiTwitter.php';
include 'EpiTwitter/TwitterConfig.php';
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
$TwitterLoginUrl=$twitterObj->getAuthorizationUrl();
header("Location: $TwitterLoginUrl");
?>

index.php
Contains PHP code, hyperlink to TwitterLogin.php file.
<?php
session_start();
//Login session check
if(!empty($_SESSION['TwitterUsername']))
{
header("Location: home.php");
}
?>
//HTML Code
<a href="TwitterLogin.php">Login with Twitter</a>

TwitterCallback.php
Twitter application callback URL, Twitter will send all the OAuth tokens values to following file. Please follow the code comments.
<?php
include 'EpiTwitter/EpiCurl.php';
include 'EpiTwitter/EpiOAuth.php';
include 'EpiTwitter/EpiTwitter.php';
include 'EpiTwitter/TwitterConfig.php';
include("db.php");

$Twitter = new EpiTwitter($consumer_key, $consumer_secret);

if(isset($_GET['oauth_token']) || (isset($_SESSION['oauth_token']) && isset($_SESSION['oauth_token_secret'])))
{

if(empty($_SESSION['oauth_token']) && empty($_SESSION['oauth_token_secret']) )
{
$Twitter->setToken($_GET['oauth_token']);
$token = $Twitter->getAccessToken();
$_SESSION['oauth_token']=$token->oauth_token;
$_SESSION['oauth_token_secret']= $token->oauth_token_secret;
$Twitter->setToken($token->oauth_token, $token->oauth_token_secret);
}
else
{
$Twitter->setToken($_SESSION['oauth_token'],$_SESSION['oauth_token_secret']);
}

$userData= $Twitter->get_accountVerify_credentials();
$TwitterUsername=$userData->screen_name;
$TwitterFullname=$userData->name;
$_SESSION['TwitterUsername']=$TwitterUsername;
$_SESSION['TwitterFullname']=$TwitterFullname;
$oauth_token=$_SESSION['oauth_token'];
$oauth_token_secret=$_SESSION['oauth_token_secret'];
//Checking user availability.
$tw_sql=mysqli_query($connection,"SELECT user_id FROM TwitterUpdate WHERE uname='$TwitterUsername'");

if(mysqli_num_rows($tw_sql) == 0)
{
//Insert values into TwitterUpdate table
$sql=mysqli_query($connection,"INSERT into TwitterUpdate(uname,name,oauth_token,oauth_token_secret) VALUES ('$TwitterUsername','$TwitterFullname','$oauth_token','$oauth_token_secret');");
}
header('Location: home.php'); //Redirecting Page
 
}
else
{
header('Location: index.php');
}
?>


home.php
This code contains PHP, Javascript(jquery) and simple HTML. Here $("#submit").click(function(){}- submit is the id name of input button. Using $("#message").val("") calling the textarea value.
<?php
session_start();
if(empty($_SESSION['TwitterUsername']))
{
header('Location: index.php');
}
?>
<script  src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function()
{
//Displaying character count 
$("#message").keyup(function()
{
var A=$.trim($(this).val());
$("#count").html(A.length);
});

//Ajax message update to Twitter.
$("#submit").click(function()
{
var A=$.trim($("#message").val());
var dataString = 'TwitterMessage='+ A ;

if(A.length<=145)
{
$.ajax({
type: "POST",
url: "TwitterUpdate.php", //Ajax Call
data: dataString,
cache: false,
beforeSend: function()
{
$("#submit").val("Updating...");
},
success: function(data)
{
var B=$("#username").val();
var C='https://twitter.com/'+B+'/status/'+data;
$("#link").html('<a href="'+C+'" target="_blank">'+C+'</a>');
$("#submit").val("Post to Twitter");
$("#message").val("").focus();
$("#count").html('0');
}
});
}
else
{
alert("Maximum 145 characters.");
}

return false;
});

});
</script>
//HTML Code
<h1>Welcome to <?php echo $_SESSION['TwitterFullname']; ?></h1>
<form method="post" action="">
<textarea id="message"></textarea><span id="count">0</span>
<input type="hidden" value="<?php echo $_SESSION['TwitterUsername']; ?>" id="username"/>
<input type="submit" id="submit"  value="Post to Twitter"/>
<div id="link"></div>
</form>
<a href="TwitterLogout.php">Logout</a>

TwitterUpdate.php
Twitter OAuth status update file.
<?php
include 'EpiTwitter/EpiCurl.php';
include 'EpiTwitter/EpiOAuth.php';
include 'EpiTwitter/EpiTwitter.php';
include 'EpiTwitter/TwitterConfig.php';
include("db.php");
if(isset($_POST['TwitterMessage']) && !empty($_SESSION['TwitterUsername']))
{
$message=mysql_real_escape_string($_POST['TwitterMessage']);
$TwitterUsername=$_SESSION['TwitterUsername'];
//Getting values from TwitterUpdate table. 
$tw_sql=mysqli_query($connection,"SELECT oauth_token,oauth_token_secret FROM TwitterUpdate WHERE uname='$TwitterUsername'");
$row=mysqli_fetch_array($tw_sql,MYSQLI_ASSOC);
$oauth_token=$row["oauth_token"];
$oauth_token_secret=$row["oauth_token_secret"];
if(strlen($oauth_token)>0 && strlen($oauth_token_secret)>0 )
{
$Twitter = new EpiTwitter($consumer_key, $consumer_secret);
$Twitter->setToken($oauth_token,$oauth_token_secret);
//Twitter status update
$status=$Twitter->post_statusesUpdate(array('status' => $message));
echo $status->id_str;
}
}
?>

TwitterLogout.php
Session logout this will clear all the session values and it redirect to index.php
<?php
session_start();
unset($_SESSION['TwitterUsername']);
unset($_SESSION['oauth_token']);
unset($_SESSION['oauth_token_secret']);
session_destroy();
header("location: index.php");
?>
web notification

30 comments:

  1. woow.. awesome tutorial...
    thanks srinivas

    ReplyDelete
  2. thanx brother, i like youur skillll ...

    ReplyDelete
  3. where you get this knowledge ... I love your brain = D

    ReplyDelete
  4. Hello, is to use this same method to automatically post to Twitter?
    thank you

    ReplyDelete
  5. thanks srinivas, but how you can update status with the media, for example, by adding a picture with the post?

    ReplyDelete
  6. Not related but did twitter started giving user email with this update?

    ReplyDelete

  7. Thanks for sharing this wonderful post, It is awesome.

    ReplyDelete

  8. Nice post, i hope everyone will like your post..

    ReplyDelete
  9. Thanks man! You are too awesome :D

    ReplyDelete
  10. Twitter updation using PHP, a very good post.

    ReplyDelete
  11. Thank for post, i have a problem with the script OAuth, in the code not found method post_statusesUpdate, help me pleas thank

    ReplyDelete
  12. Great tutorial about twitter oauth, i will try it later
    thanks! :)

    ReplyDelete
  13. Great tutorial! Really halpfull

    ReplyDelete
  14. Pakka codings... Thanks Bro.

    ReplyDelete
  15. Really informative and Interesting. I have a twitter account and I surely try this for once. Cheers!

    ReplyDelete
  16. I was really looking for this and i found it here. I just downloaded your script and its working fine. You saved my time and money

    Thanks

    ReplyDelete
  17. not updating my twitter status and showing fatal error: exceeded 60 seconds blah blah...

    ReplyDelete
  18. m getting this error ..
    db file is ok.. I checked many time .. I have searched 'localhost' and 'root' in my who ftp filemanager.. I not found this .. But it showing access denied for user root@localhost..
    Plz help...
    Otherwise your this script not complete

    https://twitter.com/iAm_Ginni/status/
    Warning: mysql_real_escape_string():
    Access denied for user
    'root'@'localhost' (using password: NO)
    in /home/u614060487/public_html/twtr/
    TwitterUpdate/TwitterUpdate.php on line 9 Warning: mysql_real_escape_string(): A
    link to the server could not be established
    in /home/u614060487/public_html/twtr/
    TwitterUpdate/TwitterUpdate.php on line
    9 Warning: mysqli_fetch_array() expects
    parameter 1 to be mysqli_result, boolean given in /home/u614060487/public_html/
    twtr/TwitterUpdate/TwitterUpdate.php
    on line 12

    ReplyDelete
  19. Please open the file TwitterUpdate.php and

    Replace the line :

    $message=mysql_real_escape_string($_POST['TwitterMessage']);

    With
    $message=mysqli_real_escape_string($connection, $_POST['TwitterMessage']);

    This solved the problem for me!

    Haneef Puttur


    $message=mysqli_real_escape_string($connection, $_POST['TwitterMessage']);

    ReplyDelete
  20. how can I get the user email id after login with twitter

    ReplyDelete
    Replies
    1. Twitter is not providing email id.

      Delete
    2. hello sir,
      I am using your code in my YII Project and i find some error like "Redeclared EpiTwitter class". Can you please help me to solved this error.

      Delete
  21. I am getting the following error any idea tel me
    Fatal error: Uncaught exception 'EpiTwitterException' with message '{"errors":[{"message":"Rate limit exceeded","code":88}]}' in /home/dhomeprojects/public_html/test/reset/EpiTwitter/EpiTwitter.php:279 Stack trace: #0 /home/dhomeprojects/public_html/test/reset/EpiTwitter/EpiTwitter.php(226): EpiTwitterException::raise(Object(EpiCurlManager), false) #1 /home/dhomeprojects/public_html/test/reset/EpiTwitter/EpiTwitter.php(127): EpiTwitterJson->__get('response') #2 /home/dhomeprojects/public_html/test/reset/EpiTwitter/EpiTwitter.php(109): EpiTwitter->request('GET', '/account/verify...', NULL) #3 /home/dhomeprojects/public_html/test/reset/TwitterCallback.php(28): EpiTwitter->__call('get_accountVeri...', Array) #4 /home/dhomeprojects/public_html/test/reset/TwitterCallback.php(28): EpiTwitter->get_accountVerify_credentials() #5 {main} thrown in /home/dhomeprojects/public_html/test/reset/EpiTwitter/EpiTwitter.php on line 279

    ReplyDelete
  22. hi thanks a lot for this useful post. i found all the details very well except email address of logged in user. how can i found the email address of logged in user. please help me. Thanks a lot: Praveen Kumar.

    ReplyDelete
  23. Hello, i get a problem here, please help me.

    TwitterLogin.php doesn't generate Twitter authorization url.
    the page was blank
    and i don't know where the problem is.

    ReplyDelete
  24. Hello Srinivas Tamadabhai,
    I am using your code in my YII Project.I find error like "Redclared Class EpiTwitter" Can you help me to solve this problem I want to live my project at EOD. Please Please help me.I am waiting for your favourable reply.

    ReplyDelete
  25. Hello,

    http://expertvillagemedia.com/aouths/TwitterUpdate/TwitterCallback.php?oauth_token=me0zxcccxxxxxxengAAABVd66ONY&oauth_verifier=eSsrmJzI3sLl3QEU3GvFQkaAq16kXii8

    After this one redirection the Blank screen is prompting ,Why?

    ReplyDelete

mailxengine Youtueb channel
Make in India
X