codebird-php
Warning
This project is no longer maintained. Codebird was written for the Twitter API v1.1,
which X has retired or put behind paid tiers since 2023. Most methods here no longer work,
and no fixes or releases are planned. For new projects, use a library that targets the
current X API v2.
Thanks to everyone who used and contributed to Codebird from 2010 on.
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 support@jublo.net
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 http://www.gnu.org/licenses/.
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:
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:
$cb->setToken('YOURTOKEN', 'YOURTOKENSECRET');
Or you authenticate, like this:
session_start();
if (! isset($_SESSION['oauth_token'])) {
// get the request token
$reply = $cb->oauth_requestToken([
'oauth_callback' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
]);
// store the token
$cb->setToken($reply->oauth_token, $reply->oauth_token_secret);
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
$_SESSION['oauth_verify'] = true;
// redirect to auth website
$auth_url = $cb->oauth_authorize();
header('Location: ' . $auth_url);
die();
} elseif (isset($_GET['oauth_verifier']) && isset($_SESSION['oauth_verify'])) {
// verify the token
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
unset($_SESSION['oauth_verify']);
// get the access token
$reply = $cb->oauth_accessToken([
'oauth_verifier' => $_GET['oauth_verifier']
]);
// store the token (which is different from the request token!)
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
// send to same URL, without oauth GET parameters
header('Location: ' . basename(__FILE__));
die();
}
// assign access token on each page load
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
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.
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:
$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:
\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:
- For each slash in a Twitter API method, use an underscore in the Codebird function.
Example: statuses/update maps to Codebird::statuses_update().
- For each underscore in a Twitter API method, use camelCase in the Codebird function.
Example: statuses/home_timeline maps to Codebird::statuses_homeTimeline().
- 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:
$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:
$reply = $cb->statuses_update('status=Whohoo, I just Tweeted!');
⚠️ Make sure to urlencode any parameter values that contain
query-reserved characters, like Tweeting the & sign:
$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:
$params = [
'status' => 'Fish & chips'
];
$reply = $cb->statuses_update($params);
$params = [
'status' => 'I love London',
'lat' => 51.5033,
'long' => 0.1197
];
$reply = $cb->statuses_update($params);
$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:
$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:
$reply = $cb->statuses_homeTimeline();
$data = (array) $reply;
Upon your choice, you may also get PHP arrays directly:
$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:
$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:
// 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: