Sign in with Twitter using PHP
With millions of registered users worldwide, twitter is one of the most used social networking website on the internet, we cannot overlook its importance, it can really boost registrations rate in your site. In this tutorial, we will be using Twitter API to register users on your website. I have created 3 PHP files for the tutorial : configuration, Login and process PHP files. We also need Abraham William's Twitter PHP Library, which is a widely used and known for its simplicity. I have included this library in downloadable file along with tutorial files below.Configuration
Configuration file stores your Twitter Customer key, secret and callback URL. If you haven't created Twitter application for your website, go to Twitter developer page and create one here. Once you finish creating Twitter App, you need to get your Customer key & Secret, and replace config variables in config.php file.[cc lang="php"] [/cc]Login page
Login Page (index.php) contains a login button, but you can put login button anywhere in your website. Once user clicks login, user must be redirected to process.php, from where user is sent to Twitter Auth page to obtains a request token, and again user is redirected back to process.php. On successful authorization, process.php sets details in session variables which will be used later in other pages to make GET/POST requests.Trick is very simple, if this session is not set login button must be displayed in order to redirect use to Twitter authorization page.PHP
- 1
- 2
- 3
- 4
- 5
- 6
if(isset($_SESSION['status']) && $_SESSION['status']=='verified')
{
// user is logged in
}else{
//show login button
}
Welcome '.$screenname.' (Twitter ID : '.$twitterid.'). Logout!
'; $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $oauth_token, $oauth_token_secret);//see if user wants to tweet using form. if(isset($_POST["updateme"])) { //Post text to twitter $my_update = $connection->post('statuses/update', array('status' => $_POST["updateme"])); die(''); //redirect back to index.php }//show tweet form echo ''; echo ''; echo '
';//Get latest tweets $my_tweets = $connection->get('statuses/user_timeline', array('screen_name' => $screenname, 'count' => 5)); /* echo ''; print_r($my_tweets); echo ''; */echo '
Latest Tweets : '; echo '
';}else{ //login button echo ''; }?>- '; foreach ($my_tweets as $my_tweet) { echo '
- '.$my_tweet->text.'
-'.$my_tweet->created_at.' '; } echo '