PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Zend Framework 101: Zend_Oauth

Beginning the OAuth Login Process

Another name for a web application that communicates with an OAuth server is a consumer. Likewise, the Zend_Oauth components includes a class called Zend_Oauth_Consumer. This is the class we use to communicate with Twitter.

In the previous section we created a function called getAuthConfig(). This function returns a number of configuration options that we pass directly to Zend_Oauth_Consumer when we instantiate it.

In this section we will create the login.php script for our basic application. As mentioned previously, the first stage in authenticating with an OAuth server is to get a request token. We can do so using the getRequestToken() of Zend_Oauth_Consumer. This method returns an instance of Zend_Oauth_Token_Request.

Once we have a request token we must store it temporarily then redirect the user to Twitter so they can authenticate. Listing 7 demonstrates how we can achieve this.

Listing 7 Beginning to OAuth authentication process (login.php)
<?php
    require_once('globals.php');
    require_once('Zend/Session.php');
    require_once('Zend/Oauth/Consumer.php');
 
    $consumer = new Zend_Oauth_Consumer(getAuthConfig());
 
    // fetch a request token
    $token = $consumer->getRequestToken();
 
    // save the token to session
    $session = new Zend_Session_Namespace('twitter_oauth');
    $session->token  = $token->getToken();
    $session->secret = $token->getTokenSecret();
 
    // redirect the user to Twitter
    $consumer->redirect();
?>

After retrieving the token, we write the token and secret to session so it is available after the user returns from authenticating at Twitter (we will need it again to complete the process).

The final step is to redirect the user to Twitter so they can authenticate. Calling redirect() on the consumer object takes care of this for us.

Next we will look at the callback.php script, which is used to complete the authentication process.

In This Article