Now that you already wrote your first Twittertools app – Hello Twitter – you can go ahead to try your first multi-user application, where users must authenticate with Twitter before performing some action.

When working with user authentication, you will need to use sessions. The first thing we have to add, in the beginning of the script, is the session_start function.

<?php
session_start();
?>

Since we need to output html code to the user, you may want to add some html headers at this point. Lets skip to the body section, to the script code itself.

You will not need that access_token and access_token_secret anymore. These keys will come from Twitter when user authorizes your app.

Its pretty easy. First, you need to get the authentication link from Twitter. Then, you must redirect user to this link, so he can authorize your app. After authorizing your app, the user will be redirected back to your application, to the exact url you defined at the “callback url” field on application settings (Twitter developers area). But you don’t need to worry about getting the tokens, because Twittertools does the all the job for you. Let’s see the code for authenticating the user.

<?php
require_once("lib/TwitterTools.php");
require_once("lib/TwitterOAuth.php");
require_once("lib/OAuth.php");

	/* consumer key & consumer secret - register an app to get yours at:
	 * http://dev.twitter.com/apps/new
	 */
	$consumer_key = "your_app_consumer_key";
	$consumer_secret = "your_app_consumer_secret";

	$tw = new TwitterTools($consumer_key,$consumer_secret);

	if(!$tw->state)
	{		
		//if state == 0, there's no logged user yet. lets get the auth link for him
		$request_link = $tw->getAuthLink();
		echo '<h3>Sign in with your twitter account</h3>';
		echo '<p><a href="'.$request_link.'" title="sign in with your twitter account"><img src="img/sign-in-with-twitter-d.png" /></a></p>';
	} 
	else 
	{	
                //user is logged in, do what you want to do
                $logado = 1;
		$credentials = $tw->getCredentials();

		?>
		<p>You are logged in as: <strong><?=$credentials['screen_name']?></strong> [ <a href="./?logout=1">LOGOUT</a> ]</p>
	<?
	}//else	
?>

[box type="info"] There are 3 possible states for the state property: 0 = user not logged in;  1 = user is logged in and just authorized your app and came back from Twitter. It’s the right moment for save user information on database, if you want so. 2 = user is logged in[/box]

If you don’t want to save any information about the user (as we did here), you just need to check if state == 0 to get and show the auth link (in this case, encapsuled on twitter button). The else statement contains all the actions you want to perform with the logged user.

Now, is up to you decide how the app will behave. The best approach is to put a button, something that requires an user action, to post that greeting we made in our first example. Otherwise, everytime the user reloads the page, after logged in, the update will occur.