Skip to content

Instantly share code, notes, and snippets.

@lamprosg
Last active December 12, 2015 00:18
Show Gist options
  • Select an option

  • Save lamprosg/4682968 to your computer and use it in GitHub Desktop.

Select an option

Save lamprosg/4682968 to your computer and use it in GitHub Desktop.
Twitter OAuth API with PHP
1. Register a new app at dev.twitter.com/apps/
2. Fill in the fields for your site accordingly, just be sure to select Browser in Application Type, and set
the Callback URL to something like http://blahblah.com/twitter_login.php (http://localhost/ won’t be accepted because it doesn’t have a domain name).
2. Select Read & Write. Fill in the captcha, click “Register Application,” and accept the Terms of Service.
3. You get a Consumer key and Consumer secret
4. Since we’re using Twitter to authenticate users, we’ll need a database table to store those users
//See "database_setup.sql"
5. Get twitteroauth library
Here: https://www.box.com/s/prg7zld8vw7mkmj3lkd2
or here : https://github.com/abraham/twitteroauth/tree/master/twitteroauth
6. Your sign in link will be "twitter_login.php"
7. The file "twitter_oauth.php" will be used by "twitter_login.php" to get the user's credentials and add him to the database
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`oauth_provider` varchar(10),
`oauth_uid` text,
`oauth_token` text,
`oauth_secret` text,
`username` text,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
<?php
require("twitteroauth/twitteroauth.php");
session_start();
/*The OAuth workflow starts by generating a URL for the request;
the user is redirected to that URL and is asked for authorization.
After granting it, the application redirects back to our server with two tokens in the URL parameters,
which are required for the authentication.*/
// The TwitterOAuth instance
$twitteroauth = new TwitterOAuth('YOUR_CONSUMER_KEY', 'YOUR_CONSUMER_SECRET');
//Now we’ll request the authentication tokens, saving them to the session, and redirect the user to Twitter for authorization
// Requesting authentication tokens, the parameter is the URL we will be redirected to
$request_token = $twitteroauth->getRequestToken('http://blahblah.com/twitter_oauth.php');
// Saving them into the session
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
// If everything goes well..
if($twitteroauth->http_code==200){
// Let's generate the URL and redirect
$url = $twitteroauth->getAuthorizeURL($request_token['oauth_token']);
header('Location: '. $url);
} else {
// It's a bad idea to kill the script, but we've got to know when there's an error.
die('Something wrong happened. Could not authenticate');
}
?>
<?php
require("twitteroauth/twitteroauth.php");
require("databaseconnection.php");
session_start();
//Auth verifier in the URL query data. Validate this data and redirect if one of these variables is empty.
if(!empty($_GET['oauth_verifier']) && !empty($_SESSION['oauth_token']) && !empty($_SESSION['oauth_token_secret'])){
// We've got everything we need
} else {
// Something's missing, go back to square 1
header('Location: twitter_login.php');
}
// TwitterOAuth instance, with two new parameters we got in twitter_login.php
$twitteroauth = new TwitterOAuth('YOUR_CONSUMER_KEY', 'YOUR_CONSUMER_SECRET', $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
// Let's request the access token
$access_token = $twitteroauth->getAccessToken($_GET['oauth_verifier']);
// Save it in a session var
$_SESSION['access_token'] = $access_token;
// Let's get the user's info
$user_info = $twitteroauth->get('account/verify_credentials');
//You can get the user’s id with $user_info->id
//his or her username with $user_info->screen_name
/*Now that we have the user’s info we can go ahead and register them,
but first we have to check if they exist in our database*/
$link = mysql_connect("localhost", $databaseuser, $databasepassword);
mysql_select_db($databasename) or die(mysql_error());
if(isset($user_info->error)){
// Something's wrong, go back to square 1
header('Location: twitter_login.php');
} else {
// Let's find the user by its ID
$query = mysql_query("SELECT * FROM users WHERE oauth_provider = 'twitter' AND oauth_uid = ". $user_info->id);
$result = mysql_fetch_array($query);
if (!$query)
print(mysql_error());
// If not, let's add it to the database
if(empty($result)){
$query = mysql_query("INSERT INTO users (oauth_provider, oauth_uid, username, oauth_token, oauth_secret) VALUES ('twitter', {$user_info->id}, '{$user_info->screen_name}', '{$access_token['oauth_token']}', '{$access_token['oauth_token_secret']}')");
$query = mysql_query("SELECT * FROM users WHERE id = " . mysql_insert_id());
$result = mysql_fetch_array($query);
} else {
// Update the tokens
$query = mysql_query("UPDATE users SET oauth_token = '{$access_token['oauth_token']}', oauth_secret = '{$access_token['oauth_token_secret']}' WHERE oauth_provider = 'twitter' AND oauth_uid = {$user_info->id}");
}
$_SESSION['id'] = $result['id'];
$_SESSION['username'] = $result['username'];
$_SESSION['oauth_uid'] = $result['oauth_uid'];
$_SESSION['oauth_provider'] = $result['oauth_provider'];
$_SESSION['oauth_token'] = $result['oauth_token'];
$_SESSION['oauth_secret'] = $result['oauth_secret'];
//Go the location once you'vr logged in successfully
header('Location: main.php');
}
mysql_close($link);
?>
<?php
session_start();
require("twitteroauth/twitteroauth.php");
//Get user's credentials
$user_token=$_SESSION['oauth_token'];
$user_secret=$_SESSION['oauth_secret'];
//New TwitterOAuth instance
$t = new TwitterOAuth('YOUR_CONSUMER_KEY', 'YOUR_CONSUMER_SECRET', $user_token, $user_secret);
$t->post('statuses/update', array('status' => $tweet));
?>
<?php
session_start();
require("twitteroauth/twitteroauth.php");
if(!empty($_SESSION['username']))
{
$twitteroauth = new TwitterOAuth('YOUR_CONSUMER_KEY', 'YOUR_CONSUMER_SECRET', $_SESSION['oauth_token'], $_SESSION['oauth_secret']);
}
$home_timeline = $twitteroauth->get('statuses/home_timeline');
print_r($home_timeline);
/*That will get you the timeline. You can fetch each item with a foreach loop.
However, the reference specifies some optional parameters like count, which limits how many tweets will be fetched.
In fact, get‘s second parameter is an array of every option needed,
so if you want to fetch the latest forty tweets, here’s the code:*/
$home_timeline = $twitteroauth->get('statuses/home_timeline', array('count' => 40));
/*Also, you can see somebody else’s timeline, as long as it’s not protected.
statuses/user_timeline requires either a user’s id or screen name.
If you want to check @nettuts timeline, you’ll have to use the following snippet:*/
$nettuts_timeline = $twitteroauth->get('statuses/user_timeline', array('screen_name' => 'nettuts'));
<?php
session_start();
require("twitteroauth/twitteroauth.php");
//Check if user follows @faelazo
$follows_faelazo = $twitteroauth->get('friendships/exists', array('user_a' => $_SESSION['username'], 'user_b' => 'faelazo'));
if(!$follows_faelazo)
{
echo 'You are NOT following @faelazo!';
//Follow him
$twitteroauth->post('friendships/create', array('screen_name' => 'faelazo'));
//Or UnFollow him
$twitteroauth->post('friendships/destroy', array('screen_name' => 'faelazo'));
}
?>
@lamprosg
Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment