Download the PHP package jublonet/codebird-php without Composer

On this page you can find all versions of the php package jublonet/codebird-php. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?
jublonet/codebird-php
Rate from 1 - 5
Rated 4.50 based on 2 reviews

Informations about the package codebird-php

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 [email protected]

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/.

Codacy Badge Coverage Status Travis Status

Requirements

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:

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

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.

Codebird also supports calling the oauth/invalidate_token method directly:

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:

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:

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:

Usage examples

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

Tweeting is as easy as this:

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

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

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:

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:

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

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

Uploading images and videos

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:

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:

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:

: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:

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 Direct Messages API and the Account Activity API is available there as well.

Here’s a sample for adding a Tweet using the Collections API:

TON (Twitter Object Nest) API

The TON (Twitter Object Nest) API allows implementers to upload media and various assets to Twitter. The TON API supports non-resumable and resumable upload methods based on the size of the file. For files less than 64MB, non-resumable may be used. For files greater than or equal to 64MB, resumable must be used. Resumable uploads require chunk sizes of less than 64MB.

For accessing the TON API, please adapt the following code samples for uploading:

Single-chunk upload

As you see from that sample, Codebird rewrites the special TON API headers into the reply, so you can easily access them. This also applies to the X-TON-Min-Chunk-Size and X-Ton-Max-Chunk-Size for chunked uploads:

Multi-chunk upload

Twitter Ads API

The Twitter Ads API allows partners to integrate with the Twitter advertising platform in their own advertising solutions. Selected partners have the ability to create custom tools to manage and execute Twitter Ad campaigns.

When accessing the Ads API or Ads Sandbox API, access it by prefixing your call with ads_. Watch out for the usual replacements for in-url parameters, particularly :account_id.

Tip: For accessing the Ads Sandbox API, use the ads_sandbox_ prefix, like shown further down.

Here is an example for calling the Twitter Ads API:

Multiple-method API calls

In the Twitter Ads API, there are multiple methods that can be reached by HTTP GET, POST, PUT and/or DELETE. While Codebird does its best to guess which HTTP verb you’ll want to use, it’s the safest bet to give a hint yourself, like this:

Codebird will remove the httpmethod parameter from the parameters list automatically, and set the corresponding HTTP verb.

How Do I…?

…use multiple Codebird instances?

By default, Codebird works with just one instance. This programming paradigma is called a singleton.

Getting the main Codebird object is done like this:

If you need to run requests to the Twitter API for multiple users at once, Codebird supports this as well. Instead of getting the instance like shown above, create a new object:

Please note that your OAuth consumer key and secret is shared within multiple Codebird instances, while the OAuth request and access tokens with their secrets are not shared.

…access a user’s profile image?

First retrieve the user object using

$reply = $cb->users_show("screen_name=$username");

with $username being the username of the account you wish to retrieve the profile image from.

Then get the value from the index profile_image_url or profile_image_url_https of the user object previously retrieved.

For example:

$reply['profile_image_url'] will then return the profile image url without https.

…get user ID, screen name and more details about the current user?

When the user returns from the authentication screen, you need to trade the obtained request token for an access token, using the OAuth verifier. As discussed in the section ‘Usage example,’ you use a call to oauth/access_token to do that.

The API reply to this method call tells you details about the user that just logged in. These details contain the user ID and the screen name.

Take a look at the returned data as follows:

If you need to get more details, such as the user’s latest Tweet, you should fetch the complete User Entity. The simplest way to get the user entity of the currently authenticated user is to use the account/verify_credentials API method. In Codebird, it works like this:

I suggest to cache the User Entity after obtaining it, as the account/verify_credentials method is rate-limited by 15 calls per 15 minutes.

…walk through cursored results?

The Twitter REST API utilizes a technique called ‘cursoring’ to paginate large result sets. Cursoring separates results into pages of no more than 5000 results at a time, and provides a means to move backwards and forwards through these pages.

Here is how you can walk through cursored results with Codebird.

  1. Get the first result set of a cursored method:

  2. To navigate forth, take the next_cursor_str:

  3. If $nextCursor is not 0, use this cursor to request the next result page:

To navigate back instead of forth, use the field $resultX->previous_cursor_str instead of next_cursor_str.

It might make sense to use the cursors in a loop. Watch out, though, not to send more than the allowed number of requests to followers/list per rate-limit timeframe, or else you will hit your rate-limit.

…use xAuth with Codebird?

Codebird supports xAuth just like every other authentication used at Twitter. Remember that your application needs to be whitelisted to be able to use xAuth.

Here’s an example:

Are you getting a strange error message? If the user is enrolled in login verification, the server will return a HTTP 401 error with a custom body. If you are using the send_error_codes parameter, you will receive the following error message in the response body:

Otherwise, the response body will contain a plaintext response:

When this error occurs, advise the user to generate a temporary password on twitter.com and use that to complete signing in to the application.

…know what cacert.pem is for?

Connections to the Twitter API are done over a secured SSL connection. Codebird-php checks if the Twitter API server has a valid SSL certificate. Valid certificates have a correct signature-chain. The cacert.pem file contains a list of all public certificates for root certificate authorities. You can find more information about this file at http://curl.haxx.se/docs/caextract.html.

…set the timeout for requests to the Twitter API?

For connecting to Twitter, Codebird uses the cURL library, if available. You can specify both the connection timeout and the request timeout, in milliseconds:

If you don't specify the timeout, codebird uses these values:

…disable cURL?

Codebird automatically detects whether you have the PHP cURL extension enabled. If not, the library will try to connect to Twitter via socket. For this to work, the PHP setting allow_url_fopen must be enabled.

You may also manually disable cURL. Use the following call:

…use a proxy?

Codebird allows proxy support for both cURL handles and sockets.

To activate proxy mode, use the following call:

You may also use an authenticated proxy. Use the following call:

By default, a HTTP proxy is assumed. To use a different proxy type, use the corresponding CURLPROXY_* constants, like this:

…quote a Tweet?

Quoting a Tweet is different from a Retweet because you may add your own text. The original Tweet will appear below your quote. To quote a Tweet, add a link to the original Tweet to your quote, like in this sample:


All versions of codebird-php with dependencies

PHP Build Version
Package Version
Requires php Version >=5.5.0
ext-hash Version *
ext-json Version *
lib-openssl Version *
composer/installers Version ~1.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package jublonet/codebird-php contains the following files

Loading the files please wait ....