Monday 21 April 2014

// // Leave a Comment

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");
?>

0 comments:

Post a Comment