Complete working sample for Services_Twitter OAuth in PHP PEAR

% pear install --alldeps Services_Twitter-alpha

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

<?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();
}
This entry was posted in Tweak and tagged , , , . Bookmark the permalink. Trackbacks are closed, but you can post a comment.

This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

  • About

    I'm Nobu, a web developer living in Mountain View, CA. Feel free to comment on any posts. I'm also tweeting on twitter.

  • Archives

  • Recent Posts