Installation

With Composer

The recommended and easy as pie method is Composer. Setup require in your projects composer.json file. Latest release:

composer require abraham/twitteroauth

Import the TwitterOAuth class.

require "vendor/autoload.php";

use Abraham\TwitterOAuth\TwitterOAuth;

Start making API requests.

$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token, $access_token_secret);
$content = $connection->get("account/verify_credentials");

Requirements

PHP

Versions listed as "active support" or "security fixes" are supported.

Dependencies

Authorization flow

This site is a working example. Sign in with Twitter to see the flow.

Usage

Unlike many Twitter API libraries, TwitterOAuth doesn't provide a custom function for every API method. Instead there are a couple of generic functions so that as Twitter adds features to the API you don't need to update the library. Here is an example of GET statuses/home_timeline.

HTTP
GET https://api.twitter.com/1.1/statuses/home_timeline.json?count=25&exclude_replies=true
TwitterOAuth
$statuses = $connection->get("statuses/home_timeline", ["count" => 25, "exclude_replies" => true]);

v2 API

v2 API methods are supported by setting the API Version. E.g. GET /2/users.

HTTP
GET https://api.twitter.com/2/users?id=12
TwitterOAuth
$connection = new TwitterOAuth(...);
$connection->setApiVersion('2');
$response = $connection->get('users', ['ids' => 12]);

Methods

TwitterOAuth provides a couple of minimalist wrappers around Twitter's API methods.

OAuth

Only used when authorizing access to a users account. Includes API methods like POST oauth/request_token and POST oauth/access_token.

Example
$access_token = $connection->oauth("oauth/access_token", ["oauth_verifier" => "nMznkpFRTMCuNMsmALzel9FgPlmWQDWg"]);

URL

This is a special wrapper that doesn't hit the API. It builds the URL where users will authorize access to their account at. Only used for GET oauth/authorize and GET oauth/authenticate.

Example
$url = $connection->url("oauth/authorize", ["oauth_token" => "EaQLH34YD8pgKkUiSp8RbjjOgNxIYVh7"]);

GET

API methods that are HTTP GET requests. E.g. GET search/tweets.

HTTP
GET https://api.twitter.com/1.1/search/tweets.json?q=twitterapi
TwitterOAuth
$statuses = $connection->get("search/tweets", ["q" => "twitterapi"]);

POST

API methods that are HTTP POST requests. E.g. POST statuses/update.

HTTP
POST https://api.twitter.com/1.1/statuses/update.json?status=hello%20world
TwitterOAuth
$statues = $connection->post("statuses/update", ["status" => "hello world"]);

Media

Upload images using POST media/upload. This uses the v1.1 API as there is no v2 equivalent.

Note: When creating the application in the Twitter Developer Portal, you must enable Read and Write privileges under Settings > User authentication settings, as otherwise Tweet creation will fail.

$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token, $access_token_secret);
$connection->setApiVersion(1.1);
$media1 = $connection->upload('media/upload', ['media' => '/path/to/file/kitten1.jpg']);
$media2 = $connection->upload('media/upload', ['media' => '/path/to/file/kitten2.jpg'], ['chunkedUpload' => true]);
$connection->setApiVersion(2);
$parameters = [
    'text' => 'Meow Meow Meow',
    'media' => ['media_ids' => [$media1->media_id_string, $media2->media_id_string]]
];
$result = $connection->post('tweets', $parameters, ['jsonPayload' => true]);

JSON data

Send JSON data to POST direct_messages/events/new.

$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token, $access_token_secret);
$data = [
    'event' => [
        'type' => 'message_create',
        'message_create' => [
            'target' => [
                'recipient_id' => $userId
            ],
            'message_data' => [
                'text' => 'Hello World!'
            ]
        ]
    ]
];
$result = $connection->post('direct_messages/events/new', $data, ['jsonPayload' => true]);

Streaming

Streaming is not currently supported.

Proxy

HTTP proxy support can be enabled like this.

$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token, $access_token_secret);
$connection->setProxy([
    'CURLOPT_PROXY' => '127.0.0.0',
    'CURLOPT_PROXYUSERPWD' => '',
    'CURLOPT_PROXYPORT' => 8080,
]);

Error handling

After every request you should validate it was a success.

$statues = $connection->post("statuses/update", ["status" => "hello world"]);
if (in_array ($connection->getLastHttpCode(), [200, 201])) {
    // Tweet posted successfully
} else {
    // Handle error case
}

Changing timeout settings

If you experience any timeout errors you can change the default timeout settings for cURL.

$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token, $access_token_secret);
$connection->setTimeouts(10, 15);

The first parameter corresponds to the timeout for the connect phase and the second to the maximum time the request is allowed to take.

Related projects

<twitter-user> Web Component

If you are looking for an easy way to render user profiles on websites, check out twitter-user.

<twitter-status> Web Component

If you are looking for an easy way to render tweets on websites, check out twitter-status.

TypeScript types

Easy TypeScript types for Twitter API objects with twitter-d.ts.

Test data in Ruby

Easily mock test Twitter data with Faker::Twitter .