Simple Twitter Oauth Login

This entry was posted on Monday, October 10th, 2011 and is filed under apps, PHP.

Twitter is a micro blogging website. You can enable twitter users to sign up for your website using Twitter Oauth.  Once user signs up, you can post tweets for the user and also read tweets using Token and Secret which you get.

First, you need to register a Twitter Application. Once you register application, you will get a consumer key and consumer secret.
SQL

CREATE TABLE `twitterdb` (
  `uid` int(20) NOT NULL auto_increment,
  `name` varchar(30) NOT NULL,
  `token` varchar(60) NOT NULL,
  `secret` varchar(60) NOT NULL,
  PRIMARY KEY  (`uid`),
  UNIQUE KEY `name` (`name`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Index.php


<?php
session_start();
if(isset($_GET['logout']) && $_GET['logout']="1"){
    unset($_SESSION);
    session_destroy();
    header("Location: index.php");
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Twitter Oauth Connect</title>
    </head>

    <body>

        <div style="width:600px;margin: 0 auto;">

            <h1>Twitter Oauth Connect Demo</h1>

            <p>
                <a href="http://firstamong.com.com/">First Among</a>
            </p>

            <div>
                <?php
                if (isset($_SESSION['screen_name']) && $_SESSION['screen_name'] != "") { ?>
                    Hey there <b><?php echo $_SESSION['screen_name']; ?></b>, |
                    <a href="index.php?logout=1">Logout</a>
                    <br/><br/>
                    Post a message to your timeline to test this PHP class:<br/>
                <form action="index.php" method="post">
                    <textarea name="message" cols="50" rows="10">Firstamong.com #twitter demo</textarea>
                    <br/>
                    <input type="submit" value="Tweet" name="s" />
                </form>


                <?php
                    require_once 'TwitterOauthConnect.php';
                    $TwitterOauthConnect = new TwitterOauthConnect($_SESSION['oauth_token'],$_SESSION['oauth_token_secret']);

                    if (isset($_POST['message']) && $_POST['message']!=""){
                        $message = trim(strip_tags($_POST['message']));
                        $response = $TwitterOauthConnect->post('https://api.twitter.com/1/statuses/update.json',array('status'=>$message));
                        
                    }
                    
                ?>

                <?php } else { ?>
                    <div>
                        <a href="connect.php">
                            <img src="Sign-in-with-Twitter-darker.png" alt="Sign in with Twitter" style="border: none;"/>
                        </a>
                    </div>

                <?php } ?>


            </div>

        </div>

      

    </body>
</html>

TwitterOauthConnect.php

<?php

/**
 * @author Goran Mitev
 * @version 1.0
 * @license none
 * @link http://goranmitev.com/
 */
class TwitterOauthConnect {

    /**
     * Consumer key
     *
     * @var string
     */
    private $_consumerKey = 'CONSUMER KEY';
    /**
     * Consumer secret
     *
     * @var string
     */
    private $_consumerSecret = 'CONSUMER SECRET';
    /**
     * Url for requesting Oauth token
     *
     * @var string
     */
    private $_requestTokenUrl = 'https://api.twitter.com/oauth/request_token';
    /**
     *
     * @var string
     */
    private $_accessTokenUrl = 'https://api.twitter.com/oauth/access_token';
    /**
     *
     * @var string
     */
    private $_authorizeUrl = 'https://api.twitter.com/oauth/authorize';
    /**
     * Callback url
     *
     * @var string
     */
    private $_callbackUrl = 'http://www.firstamong.com/tweet/callback.php';
    /**
     * Variable for setting custom user agent for curl requests
     *
     * @var string
     */
    private $_userAgent = 'Twitter Oauth Connect';
    /**
     * Connection timeout
     *
     * @var integer
     */
    private $_connectTimeout = 30;
    /**
     * Timeout
     *
     * @var integer
     */
    private $_timeout = 30;
    /**
     * The base string for generating an Oauth signature
     *
     * @var string
     */
    private $_baseString = '';
    /**
     * Token secret
     *
     * @var string
     */
    private $_oauthTokenSecret = '';
    /**
     * Oauth parameters
     *
     * @var array
     */
    private $_oauthParameters = array(
        'oauth_callback' => '',
        'oauth_consumer_key' => '',
        'oauth_nonce' => '',
        'oauth_signature' => '',
        'oauth_signature_method' => 'HMAC-SHA1',
        'oauth_timestamp' => '',
        'oauth_token' => '',
        'oauth_version' => '1.0',
        'oauth_verifier' => ''
    );

    /**
     * An array of POST parameters as key=>value pairs
     *
     * @var array
     */
    private $_postParameters = array();
    /**
     * An array of key=>value pairs returned as a response from a HTTP call
     *
     * @var array
     */
    public $response = array();

    /**
     * Constructor
     */
    public function __construct($oauth_token=null, $oauth_token_secret=null) {
        if ($oauth_token != null && $oauth_token_secret != null) {
            $this->_oauthParameters['oauth_token'] = $oauth_token;
            $this->_oauthTokenSecret = $oauth_token_secret;
        }
    }

    /**
     * Get Request Token
     */
    public function getRequestToken() {
        try {
            $response = $this->post($this->_requestTokenUrl);
            $this->parseResponse($response);
        } catch (Exception $e) {
            echo "Could not post to " . $this->_requestTokenUrl . "<br/>";
            echo "Error: " . $e;
        }
    }

    public function getAuthorizeUrl() {
        $this->getRequestToken();
        if (isset($this->response['oauth_token'])) {
            $url = $this->_authorizeUrl . '?oauth_token=' . $this->response['oauth_token'];
            return $url;
        } else {
            throw new Exception('No temporary oauth_token received, error in getAuthourizeUrl()');
            exit;
        }
    }

    public function getAccessToken($request_token=null, $oauth_verifier=null) {
        if ($request_token == null || $oauth_verifier == null) {
            return 'error';
        }

        // initializing additional oauth parameters
        $this->_oauthParameters['oauth_token'] = $request_token;
        $this->_oauthParameters['oauth_verifier'] = $oauth_verifier;
        $response = $this->post($this->_accessTokenUrl);
        $this->parseResponse($response);

        return $this->response['oauth_token'];
    }

    private function initParameters($baseUrl, $method) {
        if ($this->_oauthParameters['oauth_token'] == '') {
            $this->_oauthParameters['oauth_callback'] = $this->_callbackUrl;
        }

        $this->_oauthParameters['oauth_consumer_key'] = $this->_consumerKey;
        $this->_oauthParameters['oauth_nonce'] = $this->generateNonce();
        $this->_oauthParameters['oauth_timestamp'] = $this->generateOauthTimestamp();

        foreach ($this->_oauthParameters as $key => $value) {
            if ($value != '') {
                $this->_oauthParameters[$key] = $this->urlencode_rfc3986($value);
            }
        }

        if (is_array($this->_postParameters) && !empty($this->_postParameters)) {
            foreach ($this->_postParameters as $k => $v) {
                if (strncmp('@', $k, 1) !== 0) {
                    $this->_postParameters[$k] = $this->urlencode_rfc3986($v);
                } else {
                    $this->_postParameters[substr($k, 1)] = $v;
                    unset($this->_postParameters[$k]);
                }
            }
        }

        // signing
        $this->_oauthParameters['oauth_signature'] = $this->urlencode_rfc3986($this->generateOauthSignature($baseUrl, $method));
    }

    private function generateNonce() {
        $mt = microtime();
        $rand = mt_rand();
        return md5($mt . $rand);
    }

    private function generateOauthSignature($baseUrl, $method) {
        $this->generateBaseString($baseUrl, $method);
        $key = $this->getSigningKey();
        return base64_encode(hash_hmac('sha1', $this->_baseString, $key, true));
    }

    private function getSigningKey() {
        $key = $this->urlencode_rfc3986($this->_consumerSecret) . '&';
        if ($this->_oauthTokenSecret != '') {
            $key .= $this->urlencode_rfc3986($this->_oauthTokenSecret);
        }
        return $key;
    }

    private function generateBaseString($baseUrl, $method) {
        $parameters = array_merge($this->_oauthParameters, $this->_postParameters);
        ksort($parameters);
        $this->_baseString = $method . '&';
        $this->_baseString.=$this->urlencode_rfc3986($baseUrl) . '&';
        foreach ($parameters as $key => $value) {
            if ($value != '') {
                $this->_baseString.=$this->urlencode_rfc3986($key) . '%3D';
                $this->_baseString.=$this->urlencode_rfc3986($value) . '%26';
            }
        }
        $this->_baseString = rtrim($this->_baseString, '%26');
    }

    private function urlencode_rfc3986($input) {
        if (is_scalar($input)) {
            return str_replace('+', ' ', str_replace('%7E', '~', rawurlencode($input)));
        } else {
            return '';
        }
    }

    private function generateOauthTimestamp() {
        return time();
    }

    private function generateHeader($realm=null) {
        $first = true;
        $out = '';
        if ($realm) {
            $out = 'Authorization: OAuth realm="' . $this->urlencode_rfc3986($realm) . '"';
            $first = false;
        } else
            $out = 'Authorization: OAuth';

        foreach ($this->_oauthParameters as $k => $v) {
            if ($v != '') {
                if (substr($k, 0, 5) != "oauth")
                    continue;
                if (is_array($v)) {
                    throw new Exception('Arrays not supported in headers');
                }
                $out .= ( $first) ? ' ' : ',';
                $out .= $k .
                        '="' .
                        $v .
                        '"';
                $first = false;
            }
        }

        return $out;
    }

    private function parseResponse($responseString) {
        $arr = explode('&', $responseString);
        for ($i = 0; $i < count($arr); $i++) {
            $arr2 = explode('=', $arr[$i]);
            $this->response[$arr2[0]] = $arr2[1];
        }
    }

    public function httpRequest($url, $method, $postfields = NULL) {
        $ci = curl_init();
        curl_setopt($ci, CURLOPT_USERAGENT, $this->_userAgent);
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->_connectTimeout);
        curl_setopt($ci, CURLOPT_TIMEOUT, $this->_timeout);
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:', $this->generateHeader()));
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ci, CURLOPT_HEADER, FALSE);

        switch ($method) {
            case 'POST':
                curl_setopt($ci, CURLOPT_POST, TRUE);
                if (!empty($postfields)) {
                    curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
                }
                break;
            case 'DELETE':
                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
                if (!empty($postfields)) {
                    $url = "{$url}?{$postfields}";
                }
        }

        curl_setopt($ci, CURLOPT_URL, $url);
        $response = curl_exec($ci);
        curl_close($ci);
        
        return $response;
    }

    private function toUrlQuery($params=array()) {
        $query = "";
        foreach ($params as $key => $value)
            $query .= $key . "=" . $value . "&";
        $query = substr($query, 0, -1);
        return $query;
    }

    public function get($url) {
        $this->initParameters($url, 'GET');
        $response = $this->httpRequest($url, 'GET');
        return $response;
    }

    public function post($url, $params = array()) {
        if (!empty($params)) {
            $this->_postParameters = $params;
        }
        $this->initParameters($url, 'POST');
        $response = $this->httpRequest($url, 'POST', $this->toUrlQuery($this->_postParameters));
        return $response;
    }

}
?>

connect.php

<?php
session_start();

require_once 'TwitterOauthConnect.php';

$TwitterOauthConnect = new TwitterOauthConnect();

$authUrl = $TwitterOauthConnect->getAuthorizeUrl();
$_SESSION['oauth_token_secret'] = $TwitterOauthConnect->response['oauth_token_secret'];
$_SESSION['oauth_token'] = $TwitterOauthConnect->response['oauth_token'];
if($_SESSION['oauth_token']!="" && $_SESSION['oauth_token_secret']!=""){
    header("Location: ".$authUrl);
    exit;
}
?>

callback.php

<?php
session_start();
require_once 'TwitterOauthConnect.php';

// This is the callback
$_SESSION['oauth_verifier'] = $_GET['oauth_verifier'];
$_SESSION['oauth_token']=$_GET['oauth_token'];

// rebuild the object
$TwitterOauthConnect = new TwitterOauthConnect();

// this is the access token
$_SESSION['oauth_token'] = $TwitterOauthConnect->getAccessToken($_SESSION['oauth_token'],$_SESSION['oauth_verifier']);
$_SESSION['oauth_token_secret'] = $TwitterOauthConnect->response['oauth_token_secret'];
$_SESSION['user_id'] = $TwitterOauthConnect->response['user_id'];
$_SESSION['screen_name'] = $TwitterOauthConnect->response['screen_name'];

$token = $TwitterOauthConnect->getAccessToken($_SESSION['oauth_token'],$_SESSION['oauth_verifier']);
$secret= $TwitterOauthConnect->response['oauth_token_secret'];
$name = $TwitterOauthConnect->response['screen_name'];
if($token && $secret && $name)
{
	$db=mysql_connect('DATABASE NAME','twitterdb','password');
	mysql_select_db('twitterdb',$db);
	$sql = "SELECT * FROM twitterdb WHERE token = '$token' AND secret='$secret'";

	if (@mysql_num_rows($result) == 0)
	{
	$sql = "INSERT INTO twitterdb (token,secret,name) VALUES ('$token','$secret','$name')";
	$result=mysql_query($sql,$db);
	}
	if(@mysql_num_rows($result) == 1)
	{
	$sql="UPDATE twitterdb SET name='$name' WHERE token='$token' AND secret='$secret'";
	$result=mysql_query($sql,$db);
	}
	
}
	header("location:index.php");

?>

Thanks to Goran Mitev

You Might Also Like

Filed Under: apps, PHP

  • ignacio

    Thankkkks :D !!! i have some problems with GET. :c