Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
C

codebird-php

> 编程语言
Open source

Easy access to the Twitter REST API, Direct Messages API, Account Activity API, TON (Object Nest) API and Twitter Ads API — all from one PHP library.

772 stars0 likes0 views
WebsiteGitHub

About

Easy access to the Twitter REST API, Direct Messages API, Account Activity API, TON (Object Nest) API and Twitter Ads API — all from one PHP library.

codebird-php

Easy access to the Twitter REST API, Direct Messages API, Account Activity API, TON (Object Nest) API and Twitter Ads API — all from one PHP library.

Copyright (C) 2010-2018 Jublo Limited

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program. If not, see .

Requirements

  • PHP 7.1.0 or higher
  • OpenSSL extension

Summary

Use Codebird to connect to the Twitter REST API, Streaming API, Collections API, TON (Object Nest) API and Twitter Ads API from your PHP code — all using just one library. Codebird supports full 3-way OAuth as well as application-only auth.

Authentication

To authenticate your API requests on behalf of a certain Twitter user (following OAuth 1.0a), take a look at these steps:

php
require_once ('codebird.php');
\Codebird\Codebird::setConsumerKey('YOURKEY', 'YOURSECRET'); // static, see README

$cb = \Codebird\Codebird::getInstance();

You may either set the OAuth token and secret, if you already have them:

php
$cb->setToken('YOURTOKEN', 'YOURTOKENSECRET');

Or you authenticate, like this:

…

Logging out

In case you want to log out the current user (to log in a different user without creating a new Codebird object), just call the logout() method.

$cb->logout();

Codebird also supports calling the oauth/invalidate_token method directly:

$reply = $cb->oauth_invalidateToken([
    'access_token'        => '1234',
    'access_token_secret' => '5678'
]);

Application-only auth

Some API methods also support authenticating on a per-application level. This is useful for getting data that are not directly related to a specific Twitter user, but generic to the Twitter ecosystem (such as search/tweets).

To obtain an app-only bearer token, call the appropriate API:

php
$reply = $cb->oauth2_token();
$bearer_token = $reply->access_token;

I strongly recommend that you store the obtained bearer token in your database. There is no need to re-obtain the token with each page load, as it becomes invalid only when you call the oauth2/invalidate_token method.

If you already have your token, tell Codebird to use it:

php
\Codebird\Codebird::setBearerToken('YOURBEARERTOKEN');

In this case, you don't need to set the consumer key and secret. For sending an API request with app-only auth, see the ‘Usage examples’ section.

A word on your callback URL

Twitter is very restrictive about which URLs may be used for your callback URL. For example, even the presence of the ‘www’ subdomain must match with the domain that you specified in the settings of your app at https://developer.twitter.com/en/apps.

Mapping API methods to Codebird function calls

As you can see from the last example, there is a general way how Twitter’s API methods map to Codebird function calls. The general rules are:

  1. For each slash in a Twitter API method, use an underscore in the Codebird function.

Example: statuses/update maps to Codebird::statuses_update().

  1. For each underscore in a Twitter API method, use camelCase in the Codebird function.

Example: statuses/home_timeline maps to Codebird::statuses_homeTimeline().

  1. For each parameter template in method, use UPPERCASE in the Codebird function. Also don’t forget to include the parameter in your parameter list.

Examples:

  • statuses/show/:id maps to Codebird::statuses_show_ID('id=12345').
  • users/profile_image/:screen_name maps to Codebird::users_profileImage_SCREEN_NAME('screen_name=jublonet').

Usage examples

When you have an access token, calling the API is simple:

php
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']); // see above

$reply = (array) $cb->statuses_homeTimeline();
print_r($reply);

Tweeting is as easy as this:

php
$reply = $cb->statuses_update('status=Whohoo, I just Tweeted!');

:warning: Make sure to urlencode any parameter values that contain query-reserved characters, like Tweeting the & sign:

php
$reply = $cb->statuses_update('status=' . urlencode('Fish & chips'));
// will result in this:
$reply = $cb->statuses_update('status=Fish+%26+chips');

In most cases, giving all parameters in an array is easier, because no encoding is needed:

php
$params = [
  'status' => 'Fish & chips'
];
$reply = $cb->statuses_update($params);
php
$params = [
  'status' => 'I love London',
  'lat'    => 51.5033,
  'long'   => 0.1197
];
$reply = $cb->statuses_update($params);
php
$params = [
  'screen_name' => 'jublonet'
];
$reply = $cb->users_show($params);

This is the resulting Tweet sent with the code above.

Requests with app-only auth

To send API requests without an access token for a user (app-only auth), add a second parameter to your method call, like this:

php
$reply = $cb->search_tweets('q=Twitter', true);

Bear in mind that not all API methods support application-only auth.

HTTP methods (GET, POST, DELETE etc.)

Never care about which HTTP method (verb) to use when calling a Twitter API. Codebird is intelligent enough to find out on its own.

Response codes

The HTTP response code that the API gave is included in any return values. You can find it within the return object’s httpstatus property.

Dealing with rate-limits

Basically, Codebird leaves it up to you to handle Twitter’s rate limit. The library returns the response HTTP status code, so you can detect rate limits.

I suggest you to check if the $reply->httpstatus property is 400 and check with the Twitter API to find out if you are currently being rate-limited. See the Rate Limiting FAQ for more information.

Unless your return format is JSON, you will receive rate-limiting details in the returned data’s $reply->rate property, if the Twitter API responds with rate-limiting HTTP headers.

Return formats

The default return format for API calls is a PHP object. For API methods returning multiple data (like statuses/home_timeline), you should cast the reply to array, like this:

php
$reply = $cb->statuses_homeTimeline();
$data = (array) $reply;

Upon your choice, you may also get PHP arrays directly:

php
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_ARRAY);

The Twitter API natively responds to API calls in JSON (JS Object Notation). To get a JSON string, set the corresponding return format:

php
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_JSON);

Uploading images and videos

Twitter will accept the following media types, all of which are supported by Codebird:

  • PNG
  • JPEG
  • BMP
  • WebP
  • GIF
  • Animated GIF
  • Video

Tweet media can be uploaded in a 2-step process:

First you send each media to Twitter. For images, it works like this:

php
// these files to upload. You can also just upload 1 image!
$media_files = [
  'bird1.jpg', 'bird2.jpg', 'bird3.jpg'
];
// will hold the uploaded IDs
$media_ids = [];

foreach ($media_files as $file) {
  // upload all media files
  $reply = $cb->media_upload([
    'media' => $file
  ]);
  // and collect their IDs
  $media_ids[] = $reply->media_id_string;
}

Uploading videos requires you to send the data in chunks. See the next section on this.

Second, you attach the collected media ids for all images to your call to statuses/update, like this:

php
// convert media ids to string list
$media_ids = implode(',', $media_ids);

// send Tweet with these medias
$reply = $cb->statuses_update([
  'status' => 'These are some of my relatives.',
  'media_ids' => $media_ids
]);
print_r($reply);

Here is a sample Tweet sent with the code above.

More documentation for uploading media is available on the Twitter Developer site.

Remote files

Remote files received from http and https servers are supported, too:

php
$reply = $cb->media_upload(array(
  'media' => 'http://www.bing.com/az/hprichbg/rb/BilbaoGuggenheim_EN-US11232447099_1366x768.jpg'
));

:warning: URLs containing Unicode characters should be normalised. A sample normalisation function can be found at http://stackoverflow.com/a/6059053/1816603

To circumvent download issues when remote servers are slow to respond, you may customise the remote download timeout, like this:

php
$cb->setRemoteDownloadTimeout(10000); // milliseconds

Video files

Uploading videos to Twitter (≤ 15MB, MP4) requires you to send them in chunks. You need to perform at least 3 calls to obtain your media_id for the video:

  1. Send an INIT event to get a media_id draft.
  2. Upload your chunks with APPEND events, each one up to 5MB in size.
  3. Send a FINALIZE event to convert the draft to a ready-to-Tweet media_id.
  4. Post your Tweet with video attached.

Here’s a sample for video uploads:

…

Find more information about accepted media formats in the Twitter Developer docs.

:warning: When uploading a video in multiple chunks, you may run into an error The validation of media ids failed. even though the media_id is correct. This is known. Please check back in the Twitter community forums.

Twitter Streaming API

The Streaming APIs give developers low latency access to Twitter’s global stream of Tweet data. A proper implementation of a streaming client will be pushed messages indicating Tweets and other events have occurred, without any of the overhead associated with polling a REST endpoint.

To consume one of the available Twitter streams, follow these two steps:

  1. Set up a callback function that gets called for every new streaming message that arrives.

    Codebird also calls this function once per second, to allow you to work on any due tasks, and to give you the chance to cancel the stream even if no new messages appear.

  2. After creating the callback, tell Codebird about it using a callable. Then start consuming the stream.

…

You should be able to set a timeout for the streaming API using setTimeout. In addition, your callback will receive empty messages if no events occur, and you should make your function return true; in order to cancel the stream.

Find more information on the Streaming API in the developer documentation website.

Twitter Collections, Direct Messages and Account Activity APIs

Collections are a type of timeline that you control and can be hand curated and/or programmed using an API.

Pay close attention to the differences in how collections are presented — often they will be decomposed, efficient objects with information about users, Tweets, and timelines grouped, simplified, and stripped of unnecessary repetition.

Never care about the OAuth signing specialities and the JSON POST body for POST and PUT calls to these special APIs. Codebird takes off the work for you and will always send the correct Content-Type automatically.

Find out more about the Collections API in the Twitter API docs. More information on the

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHPcodebirdphpstreaming-apitwitter-api

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言