Starting authorization

Generating a request_token should only happen when a user shows intent to sign into your site. It requires making an API request to Twitter. In your implementation this page should generally have no HTML rendered and instead do a redirect to the generated URL.


First we set need to autoload the TwitterOAuth class and the need Twitter application details. We will also construct a TwitterOAuth instance with the application consumer_key and consumer_secret.

require 'vendor/autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;

define('CONSUMER_KEY', getenv('CONSUMER_KEY'));

$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);

Generating a request_token

Authorizing access to a users account through OAuth starts with getting a temporary request_token. This request_token is only good for a few minutes and will soon be forgotten about.

$request_token = $connection->oauth('oauth/request_token', array('oauth_callback' => OAUTH_CALLBACK));
Response Live
array(3) {
  string(27) "1ymXNQAAAAAAAAAbAAABXzle648"
  string(32) "SDrNAslVhtVuczC6yjo2PFX2XB8ulAV4"
  string(4) "true"


This demo site uses basic PHP sessions but you can use whatever session/storage implementation you want.

$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];

Build authorize URL

Here we are building a URL the authorizing users must navigate to in their browser. It is to Twitter's authorize page where the list of permissions being granted is displayed along with allow/deny buttons.

$url = $connection->url('oauth/authorize', array('oauth_token' => $request_token['oauth_token']));
Response Live
string(79) ""

Next step: authorize on