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("users/me");

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 /2/users/:id/timelines/reverse_chronological.

HTTP
GET https://api.x.com/2/users/12/timelines/reverse_chronological?max_results=25&exclude=replies
TwitterOAuth
$posts = $connection->get("users/12/timelines/reverse_chronological", ["max_results" => 25, "exclude" => "replies"]);

API versions

TwitterOAuth v9 only supports the v2 API and paths are relative to https://api.x.com/2/. Use TwitterOAuth v8 if you still need the v1.1 API.

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 /2/tweets/search/recent.

HTTP
GET https://api.x.com/2/tweets/search/recent?query=twitterapi
TwitterOAuth
$posts = $connection->get("tweets/search/recent", ["query" => "twitterapi"]);

POST

API methods that are HTTP POST requests. E.g. POST /2/tweets. Parameters are sent as JSON. Pass ['jsonPayload' => false] as the third argument to send them form encoded instead.

HTTP
POST https://api.x.com/2/tweets
{"text": "hello world"}
TwitterOAuth
$post = $connection->post("tweets", ["text" => "hello world"]);

Media

Upload images using POST /2/media/upload. Large files and videos can use chunked uploads.

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);
$media1 = $connection->upload('media/upload', [
    'media' => '/path/to/file/kitten.jpg',
    'media_category' => 'tweet_image',
]);
$media2 = $connection->upload('media/upload', [
    'media' => '/path/to/file/kitten.mp4',
    'media_type' => 'video/mp4',
    'media_category' => 'tweet_video',
], ['chunkedUpload' => true]);
$parameters = [
    'text' => 'Meow Meow Meow',
    'media' => ['media_ids' => [$media1->data->id, $media2->data->id]]
];
$result = $connection->post('tweets', $parameters);

Videos are processed after upload. Check progress with $connection->mediaStatus($media2->data->id) before posting.

Direct Messages

Send a message with POST /2/dm_conversations/with/:participant_id/messages.

$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token, $access_token_secret);
$result = $connection->post("dm_conversations/with/$userId/messages", ['text' => 'Hello World!']);

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.

$post = $connection->post("tweets", ["text" => "hello world"]);
if ($connection->getLastHttpCode() === 201) {
    // Post created 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 .