Twitter OAuth (PHP): Need good, basic example to get started

Viewed 39138

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.

6 Answers

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.

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"
      }
    }
    */

}
Related