Complete working sample for Services_Twitter OAuth in PHP PEAR

You can get some sample codes for Services_Twitter with OAuth from php doc, but it’s not a complete code. I rewrote some parts.

% pear install --alldeps Services_Twitter-alpha
<?php
if (isset($_GET['clear'])) { // sometimes you need to clear session, just access ?clear=1
    session_start();
    $_SESSION = array();
    session_destroy();
    die('session has been cleared.');
}
 
 
define('CONSUMER_KEY', '***');
define('CONSUMER_SECRET', '***');
 
 
require_once 'Services/Twitter.php';
require_once 'HTTP/OAuth/Consumer.php';
 
try {
    session_start();
 
    if (isset($_SESSION['token2'], $_SESSION['token_secret2'])) {
        $twitter = new Services_Twitter;
        $oauth = new HTTP_OAuth_Consumer(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['token2'], $_SESSION['token_secret2']);
        $twitter->setOAuth($oauth);
        print_r($twitter->statuses->home_timeline());
 
    } else if (isset($_SESSION['token'], $_SESSION['token_secret'], $_GET['oauth_verifier'])) {
        $twitter = new Services_Twitter;
        $oauth = new HTTP_OAuth_Consumer(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['token'], $_SESSION['token_secret']);
        $oauth->getAccessToken('http://twitter.com/oauth/access_token', $_GET['oauth_verifier']);
        $twitter->setOAuth($oauth);
 
        $_SESSION['token2'] = $oauth->getToken();
        $_SESSION['token_secret2'] = $oauth->getTokenSecret();
 
        $msg = $twitter->statuses->update("I'm coding with PEAR right now!");
        print_r($msg);
 
    } else {
        $oauth = new HTTP_OAuth_Consumer(CONSUMER_KEY, CONSUMER_SECRET);
        $oauth->getRequestToken('http://twitter.com/oauth/request_token', 'http://zuzara.com/twitter_oauth.php'); // callback URL should be the same as that you registered at http://twitter.com/apps/new
 
        $_SESSION['token']        = $oauth->getToken();
        $_SESSION['token_secret'] = $oauth->getTokenSecret();
 
        $url = $oauth->getAuthorizeUrl('http://twitter.com/oauth/authorize');
 
        http_redirect($url); // function from pecl_http
    }
 
} catch (Exception $e) {
    echo $e->getMessage();
}

ref.
Getting 401 on Twitter OAuth POST requests

related article.
How to Make an Autobot on Twitter with OAuth, not Basic Authentication

This entry was posted in Create and tagged , , , . Bookmark the permalink. Both comments and trackbacks are currently closed.