Loading repository data…
Loading repository data…
jublo / repository
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.
A transparent discovery signal based on current public GitHub metadata.
This score does not audit code, security, maintainers, documentation quality, or suitability. Verify the repository and its current documentation before adoption.
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/.
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.
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']);
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'
]);
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.
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.
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:
Example: statuses/update maps to Codebird::statuses_update().
Example: statuses/home_timeline maps to Codebird::statuses_homeTimeline().
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').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!');
:warning: 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.
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.
Never care about which HTTP method (verb) to use when calling a Twitter API. Codebird is intelligent enough to find out on its own.
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.
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.
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);
Twitter will accept the following media types, all of which are supported by Codebird:
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:
// 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 received from http and https servers are supported, too:
$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:
$cb->setRemoteDownloadTimeout(10000); // milliseconds
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:
INIT event to get a media_id draft.APPEND events, each one up to 5MB in size.FINALIZE event to convert the draft to a ready-to-Tweet media_id.Here’s a sample for video uploads:
$file = 'demo-video.mp4';
$size_bytes = filesize($file);
$fp = fopen($file, 'r');
// INIT the upload
$reply = $cb->media_upload([
'command' => 'INIT',
'media_type' => 'video/mp4',
'total_bytes' => $size_bytes
]);
$media_id = $reply->media_id_string;
// APPEND data to the upload
$segment_id = 0;
while (! feof($fp)) {
$chunk = fread($fp, 1048576); // 1MB per chunk for this sample
$reply = $cb->media_upload([
'command' => 'APPEND',
'media_id' => $media_id,
'segment_index' => $segment_id,
'media' => $chunk
]);
$segment_id