38

Using Facebook's PHP SDK, I was able to get Facebook login working pretty quickly on my website. They simply set a $user variable that can be accessed very easily.

I've had no such luck trying to get Twitter's OAuth login working... quite frankly, their github material is confusing and useless for someone that's relatively new to PHP and web design, not to mention that many of the unofficial examples I've tried working through are just as confusing or are outdated.

I really need some help getting Twitter login working--I mean just a basic example where I click the login button, I authorize my app, and it redirects to a page where it displays the name of the logged in user.

I really appreciate your help.

EDIT I'm aware of the existence of abraham's twitter oauth but it provides close to no instructions whatsoever to get his stuff working.

tnw
  • 13,521
  • 15
  • 70
  • 111
  • 1
    Yeah I've really been looking for one of these that works, too. So many seems to just give examples that don't work. – cfrederich Jul 01 '11 at 16:01
  • are you against using frameworks like the zend framework? if not there are some working examples with it. – BRampersad Jul 01 '11 at 16:18

6 Answers6

32

this one is the basic example of getting the url for authorization and then fetching the user basic info when once u get back from twitter

<?php
session_start();
//add autoload note:do check your file paths in autoload.php
require "ret/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
//this code will run when returned from twiter after authentication
if(isset($_SESSION['oauth_token'])){
  $oauth_token=$_SESSION['oauth_token'];unset($_SESSION['oauth_token']);
  $consumer_key = 'your consumer key';
  $consumer_secret = 'your secret key';
  $connection = new TwitterOAuth($consumer_key, $consumer_secret);
 //necessary to get access token other wise u will not have permision to get user info
  $params=array("oauth_verifier" => $_GET['oauth_verifier'],"oauth_token"=>$_GET['oauth_token']);
  $access_token = $connection->oauth("oauth/access_token", $params);
  //now again create new instance using updated return oauth_token and oauth_token_secret because old one expired if u dont u this u will also get token expired error
  $connection = new TwitterOAuth($consumer_key, $consumer_secret,
  $access_token['oauth_token'],$access_token['oauth_token_secret']);
  $content = $connection->get("account/verify_credentials");
  print_r($content);
}
else{
  // main startup code
  $consumer_key = 'your consumer key';
  $consumer_secret = 'your secret key';
  //this code will return your valid url which u can use in iframe src to popup or can directly view the page as its happening in this example

  $connection = new TwitterOAuth($consumer_key, $consumer_secret);
  $temporary_credentials = $connection->oauth('oauth/request_token', array("oauth_callback" =>'http://dev.crm.alifca.com/twitter/index.php'));
  $_SESSION['oauth_token']=$temporary_credentials['oauth_token'];       $_SESSION['oauth_token_secret']=$temporary_credentials['oauth_token_secret'];$url = $connection->url("oauth/authorize", array("oauth_token" => $temporary_credentials['oauth_token']));
// REDIRECTING TO THE URL
  header('Location: ' . $url); 
}
?>
zoomi
  • 602
  • 8
  • 13
  • 4
    This worked nicely. Literally just copied and pasted updated the consumer keys and return url and it ran as expected. – Gene Kelly May 31 '15 at 19:30
  • Awesome!! I searched through the internet all day long for the past two days. But I was only getting the older twitteroauth codes. Kudos! This worked as smooth as butter!! – Kaustav Banerjee Jan 28 '16 at 14:49
  • "add autoload note:do check your file paths in autoload.php" What must we check ? What I am supposed to modify in this file ? – Fred37b Oct 27 '16 at 11:19
  • how would you test this on a local computer? It should be possible to omit the callback part of the code since this is not required for java libraries (twitter4j for example) – vanomart Oct 30 '16 at 10:07
  • @Fred37b path of your files where you have placed your autoload file make sure the path is the same in autoload.php – zoomi Oct 31 '16 at 05:47
  • This works really great, although my `oauth_token` keeps expiring and everytime I refresh I have to let the app authorize it. Is there a way to keep fetching tweets for a longer periods withough constant authorization from twitter. – Sanjok Gurung Feb 21 '18 at 13:09
28

I just tried abraham's twitteroauth from github and it seems to work fine for me. This is what I did

  1. git clone https://github.com/abraham/twitteroauth.git
  2. Upload this into your webhost with domain, say, www.example.com
  3. Go to Twitter Apps and register your application. The changes that you need are (assuming that you will use abraham's twitteroauth example hosted at http://www.example.com/twitteroauth)
    a) Application Website will be http://www.example.com/twitteroauth
    b) Application type will be browser
    c) Callback url is http://www.example.com/twitteroauth/callback.php (Callback.php is included in the git source)
  4. Once you do this, you will get the CONSUMER_KEY and CONSUMER_SECRET which you can update in the config.php from the twitteroauth distribution. Also set the callback to be the same as http://www.example.com/twitteroauth/callback.php

Thats it. If you now navigate to http://www.example.com/twitteroauth, you will get a "Signin with Twitter", that will take you to Twitter , authorize the request and get you back to the index.php page.

EDIT: Example will not work but do not worry. Follow the above steps and upload to server. Make sure you rename the file from github repository i.e. config-sample.php->config.php

if you want to see a working sample, find it here

Andy
  • 49,085
  • 60
  • 166
  • 233
rajasaur
  • 5,340
  • 2
  • 27
  • 22
2

Here is the step by step guide to integrate Twitter OAuth API to Web-application using PHP. Please following tutorial.

http://www.smarttutorials.net/sign-in-with-twitter-oauth-api-using-php/

You need to create Twitter App First By going thorugh following URL

https://apps.twitter.com/

Then you need to provide necessary information for the twitter app. Once your provided all the information and then save it. You will get Twitter application Consumer Key and Consumer secret.

Please download the source file from above link, and just replace TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET and TWITTER_OAUTH_CALLBACK with your Consumer Key (API Key), Consumer Secret (API Secret) and callback URL. Then upload this to your server. Now it will work successfully.

muni
  • 1,362
  • 2
  • 19
  • 21
  • Thank you for adding this! It's an old question of mine but is apparently still useful as a reference. – tnw Nov 10 '14 at 15:11
2

Here are some OAuth 1.0A PHP libraries with examples:

Twitter async provides documentation on how to simply sign in a user as you asked for.

Jon
  • 2,932
  • 2
  • 23
  • 30
0

Abraham's Twitteroauth has a working demo here: https://github.com/abraham/twitteroauth-demo

Following the steps in the demo readme worked for me. In order to run composer on macOS I had to do this after installing it: mv composer.phar /usr/local/bin/composer

IMO the demo could be a lot simpler and should be included in the main twitteroauth repo.

Felix Turner
  • 1,345
  • 1
  • 9
  • 8
0

I recently had to post new tweets to Twitter via PHP using V2 of their API but couldn’t find any decent examples online that didn’t use V1 or V1.1. I eventually figured it out using the great package TwitterOAuth.

Install this package via composer require abraham/twitteroauth first (or manually) and visit developer.twitter.com, create a new app to get the credentials needed to use the API (see below). Then you can post a tweet based on the code below.

use Abraham\TwitterOAuth\TwitterOAuth;

// Connect
$connection = new TwitterOAuth($twitterConsumerKey,             // Your API key
                               $twitterConsumerSecret,          // Your API secret key
                               $twitterOauthAccessToken,        // From your app created at https://developer.twitter.com/
                               $twitterOauthAccessTokenSecret); // From your app created at https://developer.twitter.com/

// Set API version to 2                           
$connection->setApiVersion('2');

// POST the tweet; the third parameter must be set to true so it is sent as JSON
// See https://developer.twitter.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/post-tweets for all options
$response = $connection->post('tweets', ['text' => 'Hello Twitter'], true);

if (isset($response['title']) && $response['title'] == 'Unauthorized') {

    // Handle error

} else {

    var_dump($response);

    /*
    object(stdClass)#404 (1) {
      ["data"]=>
      object(stdClass)#397 (2) {
        ["id"]=>
        string(19) "0123456789012345678"
        ["text"]=>
        string(13) "Hello Twitter"
      }
    }
    */

}
M.Ali El-Sayed
  • 1,608
  • 20
  • 23