Sainath Krishnan
Sainath Krishnan

Reputation: 2139

Creating a php function for twitter oAuth

I have successfully implemented a sign in using twitter page, which shows a login button that redirects to twitter, allows the user to login and approve my app, and then redirects back.

My question is : Is there any way to change this to a function call structure instead? Ideally the function called through a button click on index.php, would open a popup where they can log into twitter, authorize the app, and close it, while index.php itself has recieved the function's return.

If this is possible, do I just put the whole code of process.php (minus the includes) into the function, and call it?

For example, the call on index.php $name_twitter = get_twitter_handle();

and the function being

function get_twitter_handle(){
//the code of process.php
return $screen_name
}

Following is my code, which works perfectly but is not of function call format.

Code for Process.php

<?php
session_start();
include_once("config.php");
include_once("inc/twitteroauth.php");

if (isset($_REQUEST['oauth_token']) && $_SESSION['token']  !== $_REQUEST['oauth_token']) {

    // if token is old, distroy any session and redirect user to index.php
    session_destroy();
    header('Location: ./index.php');

}elseif(isset($_REQUEST['oauth_token']) && $_SESSION['token'] == $_REQUEST['oauth_token']) {

    // everything looks good, request access token
    //successful response returns oauth_token, oauth_token_secret, user_id, and screen_name
    $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['token'] , $_SESSION['token_secret']);
    $access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
    if($connection->http_code=='200')
    {
        //redirect user to twitter
        $_SESSION['status'] = 'verified';
        $_SESSION['request_vars'] = $access_token;

        // unset no longer needed request tokens
        unset($_SESSION['token']);
        unset($_SESSION['token_secret']);
        header('Location: ./index.php');
    }else{
        die("error, try again later!");
    }

}else{

    if(isset($_GET["denied"]))
    {
        header('Location: ./index.php');
        die();
    }

    //fresh authentication
    $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
    $request_token = $connection->getRequestToken(OAUTH_CALLBACK);

    //received token info from twitter
    $_SESSION['token']          = $request_token['oauth_token'];
    $_SESSION['token_secret']   = $request_token['oauth_token_secret'];

    // any value other than 200 is failure, so continue only if http code is 200
    if($connection->http_code=='200')
    {
        //redirect user to twitter
        $twitter_url = $connection->getAuthorizeURL($request_token['oauth_token']);
        header('Location: ' . $twitter_url);
    }else{
        die("error connecting to twitter! try again later!");
    }
}
?>

Code for Index.php

<?php
session_start();
include_once("config.php");
include_once("inc/twitteroauth.php");
?>
<html>
<head>
<title>Verify Twitter Handle</title>
</head>
<body>
<?php
if(isset($_SESSION['status']) && $_SESSION['status']=='verified') 
{   //Success, redirected back from process.php with verified status.
    //retrive variables
    $screenname         = $_SESSION['request_vars']['screen_name'];
    echo $screenname;
    echo '<br>';
}else{
    //login button
    echo '<a href="process.php"><img src="images/sign-in-with-twitter-l.png" width="151" height="24" border="0" /></a>';
}
?>
</body>
</html>

Upvotes: 1

Views: 440

Answers (2)

user2560539
user2560539

Reputation:

session_start();
include_once("config.php");
include_once("inc/twitteroauth.php");
   function get_twitter_handle(){
    if (isset($_REQUEST['oauth_token']) && $_SESSION['token']  !== $_REQUEST['oauth_token']) {

        // if token is old, distroy any session and redirect user to index.php
        session_destroy();
        header('Location: ./index.php');

    }elseif(isset($_REQUEST['oauth_token']) && $_SESSION['token'] == $_REQUEST['oauth_token']) {

        // everything looks good, request access token
        //successful response returns oauth_token, oauth_token_secret, user_id, and screen_name
        $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['token'] , $_SESSION['token_secret']);
        $access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
        if($connection->http_code=='200')
        {
            //redirect user to twitter
            $_SESSION['status'] = 'verified';
            $_SESSION['request_vars'] = $access_token;

            // unset no longer needed request tokens
            unset($_SESSION['token']);
            unset($_SESSION['token_secret']);
            header('Location: ./index.php');
        }else{
            die("error, try again later!");
        }

    }else{

        if(isset($_GET["denied"]))
        {
            header('Location: ./index.php');
            die();
        }

        //fresh authentication
        $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
        $request_token = $connection->getRequestToken(OAUTH_CALLBACK);

        //received token info from twitter
        $_SESSION['token']          = $request_token['oauth_token'];
        $_SESSION['token_secret']   = $request_token['oauth_token_secret'];

        // any value other than 200 is failure, so continue only if http code is 200
        if($connection->http_code=='200')
        {
            //redirect user to twitter
            $twitter_url = $connection->getAuthorizeURL($request_token['oauth_token']);
            header('Location: ' . $twitter_url);
        }else{
            die("error connecting to twitter! try again later!");
        }
    }
    }
?>
<html>
<head>
<title>Verify Twitter Handle</title>
</head>
<body>
<?php
    get_twitter_handle();
if(isset($_SESSION['status']) && $_SESSION['status']=='verified') 
{   //Success, redirected back from process.php with verified status.
    //retrive variables
    $screenname         = $_SESSION['request_vars']['screen_name'];
    echo $screenname;
    echo '<br>';
}else{
    //login button
    echo '<a href="index.php"><img src="images/sign-in-with-twitter-l.png" width="151" height="24" border="0" /></a>';
}
?>
</body>
</html>

Upvotes: 3

mirabilos
mirabilos

Reputation: 5317

PHP has no state across page loads, except for cookies, which its native sessions also use.

The logic to open a pop-up in the browser require you to send a page to the browser already, so no, you cannot run anything that involves the browser to do anything in a function before your normal page logic.

One thing you can do is to redirect to yourself. Just have a function that you always call, say check_auth(), that does nothing if the current session is already logged in, and does the magic including a redirect to the same site plus exit(0); at its end, otherwise.

Upvotes: 1

Related Questions