Twitter OAuth Status Update New Tweet 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.


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

Hướng dẫn bình luận

Mọi người để lại bình luận góp ý, nhận xét về những bài viết mà mình chia sẽ văn minh lịch sự hay kích động, Không spam, không chèn link quảng cáo, bán hàng, Không sử dụng từ ngữ thô tục, xúc phạm, kích động, Link chỉ được phép khi thực sự liên quan đến nội dung bài viết, Không mạo danh người khác hoặc sử dụng email giả, Bình luận vi phạm sẽ bị xóa không cần thông báo trước.
Mọi người lưu ý răng, nếu muốn chia sẽ code ở bình luần thì cần mã hóa code trước khi bỏ vào khung nhé. :)
⑴ Chèn ℂ𝕤𝕤 theo mẫu : [pre css] ℂ𝕤𝕤 [/pre]
⑵ Chèn ℍ𝕥𝕞𝕝 theo mẫu : [pre html] ℍ𝕥𝕞𝕝 [/pre]
⑶ Chèn 𝕁𝕒𝕧𝕒𝕤𝕔𝕣𝕚𝕡𝕥 theo mẫu : [pre js] 𝕁𝕒𝕧𝕒𝕤𝕔𝕣𝕚𝕡𝕥 [/pre]

🖼️ Chèn 𝕀𝕞𝕒𝕘𝕖 theo mẫu : [img] 𝕃𝕚𝕟𝕜 𝕀𝕞𝕒𝕘𝕖 [/img]
🎞️ Chèn Video 𝕐𝕠𝕦𝕥𝕦𝕓𝕖 theo mẫu : [youtube] 𝕃𝕚𝕟𝕜 𝕪𝕠𝕦𝕥𝕦𝕓𝕖 [/youtube]

Đăng nhận xét

@Bloggers Community

@Catalogics

CSS (31) Google (7)

@Total Pageviews