PHP Twitter Application tutorial

Creating Twitter Apps in PHP

In this post we will look into accessing Twitter REST API in PHP. This can be useful if you need to post Tweets from your PHP application or anaylze, search Tweets. In the following examples we will use the twitter-api-php PHP wrapper for Twitter v1.1 API. Although there are a few wrappers around, this one I like for its simplicity.

Installation

If you use composer, here’s what you need to add to your composer.json file to have TwitterAPIExchange.php (Twitter PHP wrapper) automatically imported into your vendor’s folder:

{
    "require": {
        "j7mbo/twitter-api-php": "dev-master"
    }
}

You’ll then need to run ‘composer install’.

If you don’t use composer, just download the zip from git and include TwitterAPIExchange.php in your application path.

Registering your Twitter app

Before writing any code, you will first need to create a Twitter app and register it onhttps://apps.twitter.com/. You will be greeted with the following screen. (The following screenshot shows you an existing app. If this is your first app than the page will be blank).

twitter-app-1

Click on the ‘Create New App’ button and enter the required details in the fields provided. Leave the ‘Callback URL’ field blank for now. Once the app is created, click on the app name and note down the various access and security tokens, we will be needing these later. Change your Access Level to ‘Read and Write’. ‘Read Only’ access does not allow you to update, add or delete Tweets. If your purpose is to only read tweet data, it is safer to set the Access Level to ‘Read Only’.

Note that you will need to regenerate the access tokens if you change the Access Levels anytime and modify the same in your PHP code.

twitter-app-2

Accessing the Twitter API from PHP

Now that you have created and registered a Twitter app, we can now use PHP to acccess the API. First include the ‘TwitterAPIExchange.php’ class and set various security tokens collected earlier.

require_once('TwitterAPIExchange.php');
 
$settings = array(
    'oauth_access_token' => "YOUR_ACCESS_TOKEN",
    'oauth_access_token_secret' => "YOUR_ACCESS_TOKEN_SECRET",
    'consumer_key' => "YOUR_CONSUMER_KEY",
    'consumer_secret' => "YOUR_CONSUMER_SECRET"
);

For this example we will be using the ‘https://api.twitter.com/1.1/statuses/user_timeline.json‘ resource url. This returns a collection of the most recent Tweets posted by the user indicated by the screen_name or user_id parameters. This particular method is one of the dozens of various methods available to access and modify Twitter data; others can be found here.

A complete GET request method is shown below. Here we are requesting the recent 3 tweets for the user ‘johndoe123’.

$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$requestMethod = "GET";
$getfield = '?screen_name=johndoe123&count=3';

Once we specify the request methods and fields, we can call Twitter.

$twitter = new TwitterAPIExchange($settings);
 
$response = $twitter->setGetfield($getfield)
                    ->buildOauth($url, $requestMethod)
                    ->performRequest();

The complete code is shown below.

<?php
 
require_once('TwitterAPIExchange.php');
 
$settings = array(
    'oauth_access_token' => "YOUR_ACCESS_TOKEN",
    'oauth_access_token_secret' => "YOUR_ACCESS_TOKEN_SECRET",
    'consumer_key' => "YOUR_CONSUMER_KEY",
    'consumer_secret' => "YOUR_CONSUMER_SECRET"
);
 
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$requestMethod = "GET";
$getfield = '?screen_name=johndoe123&count=3';
 
$twitter = new TwitterAPIExchange($settings);
 
$response = $twitter->setGetfield($getfield)
                    ->buildOauth($url, $requestMethod)
                    ->performRequest();
 
print_r($response);

Executing the above code will return the recent 3 tweets for the given user in JSON format. You can specify the number of tweets to return using the ‘count parameter. The maximum that can be returned is 200.

$getfield = '?screen_name=johndoe123&count=3';

Note that all GET fields for this method are optional. Not specifying any GET parameters will return 20 recent tweets for the current user, i.e the user with the given access tokens. You can query without the GET parameters as shown below.

$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$requestMethod = "GET";
 
$twitter = new TwitterAPIExchange($settings);
 
$response = $twitter->buildOauth($url, $requestMethod)
                    ->performRequest();
 
print_r($response);

Also, the response is returned in JSON, so will need to decode the JSON first before working further.

$tweets = json_decode($response);
print_r($tweets);

The tweet is stored in the ‘text’ field of the response, so we can enumerate all returned tweets with the following. Various other fields can be accessed in similiar manner.

$tweets = json_decode($response);
 
foreach($tweets as $tweet)
{
    echo $tweet->text . PHP_EOL;
}

Posting a new Tweet

Posting a new Tweet can be done with the following code, which uses a POST method instead of a GET. The initial code remains the same.

<?php
 
$url = "https://api.twitter.com/1.1/statuses/update.json";
 
$requestMethod = 'POST'; 
 
$postfields = array(
    'status' => 'Testing Twitter app'
);
 
$twitter = new TwitterAPIExchange($settings);
 
$response = $twitter->buildOauth($url, $requestMethod)
                   ->setPostfields($postfields)
                   ->performRequest();
 
print_r($response);

There are additoinal parameter you can use, the details for which are given here.

Searching for Tweets

Searching for Tweets based on a query is as easy as the above examples. Here in the following example we query for the ‘laravel’ keyword and ask o return 10 statuses.

$url = "https://api.twitter.com/1.1/search/tweets.json";
 
$requestMethod = "GET";
 
$getfield = '?q=laravel&count=10';
 
$twitter = new TwitterAPIExchange($settings);
$response = $twitter->setGetfield($getfield)
                    ->buildOauth($url, $requestMethod)
                    ->performRequest();
 
$tweets = json_decode($response);
 
foreach($tweets->statuses as $tweet)
{
    echo $tweet->text . PHP_EOL;
}

API rate limits

One important point to consider when creating your app is of rate limiting. Twitter limits the rate at which you query using their API. For example search will be rate limited at 180 queries per 15 minute window. More information can be found here.

Important Note

If the above examples do not work you will have to make a small change in ‘TwitterAPIExchange.php’. The curl processing part (around line 192) requires the line ‘CURLOPT_SSL_VERIFYPEER => false,’ to be added. So the curl part in the file should read the following.

        $options = array( 
            CURLOPT_HTTPHEADER => $header,
            CURLOPT_HEADER => false,
            CURLOPT_URL => $this->url,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 10,
        );

 

Youtube Vimeo on click play pause api javascript

Play and Pause Buttons for YouTube and Vimeo Videos (via Their APIs)

Sometimes you just need to start a video playing by some user interaction on the page other than clicking right on that video itself. Perhaps a “Play Video” button of your own creation lives on your page and you want to start that video when that button is clicked. That’s JavaScript territory. And if that video is a YouTube or Vimeo video, we’ll need to make use of the APIs they provide. No problem.

For these examples, we’ll assume you’ve already picked out a video and you’re going to put it on the page in an

Tutorial source: CSS-Tricks

For YouTube

1. Make sure the iframe src URL has ?enablejsapi=1 at the end

Like this:

<iframe src="//www.youtube.com/embed/FKWwdQu6_ok?enablejsapi=1" frameborder="0" allowfullscreen id="video"></iframe>

I also put an id attribute on the iframe so it will be easy and fast to target with JavaScript.

2. Load the YouTube Player API

You could just link to it in a <script>, but all their documentation shows loading it async style, which is always good for third-party scripts, so let’s do that:

// Inject YouTube API script
var tag = document.createElement('script');
tag.src = "//www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

3. Create a global function called onYouTubePlayerAPIReady

This is the callback function that the YouTube API will call when it’s ready. It needs to be named this.

function onYouTubePlayerAPIReady() {

}

It’s likely you have some structure to your JavaScript on your page, so generally I’d recommend just having this function call another function that is inside your organizational system and get going on the right track right away. But for this tutorial, let’s just keep it soup-y.

4. Create the Player object

This is the object that has the ability to control that video. We’ll create it using the id attribute on that iframe in our HTML.

var player;

function onYouTubePlayerAPIReady() {
  // create the global player from the specific iframe (#video)
  player = new YT.Player('video', {
    events: {
      // call this function when player is ready to use
      'onReady': onPlayerReady
    }
  });
}

Another callback!

5. Create the “player ready” callback and bind events

We named this function when we created the player object. It will automatically be passed the event object, in which event.target is the player, but since we already have a global for it let’s just use that.

Here we bind a simple click event to an element on the page with the id #play-button (whatever custom button you want) and call the player object’s playVideo method.

function onPlayerReady(event) {
  
  // bind events
  var playButton = document.getElementById("play-button");
  playButton.addEventListener("click", function() {
    player.playVideo();
  });
  
  var pauseButton = document.getElementById("pause-button");
  pauseButton.addEventListener("click", function() {
    player.pauseVideo();
  });
  
}

All Together Now

And that’ll do it! Here’s a demo:

I used a little SVG templating in there for the buttons just for fun.

For Vimeo

1. Make sure the iframe src URL has ?api=1 at the end

<iframe src="//player.vimeo.com/video/80312270?api=1" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen id="video"></iframe>

I also put an id attribute on the iframe so it will be easy and fast to target with JavaScript.

2. Load the “froogaloop” JS library

The Vimeo player API actually works by sending commands through postMessage right to the iframe. You don’t need the froogaloop library to do that, but postMessage has some inherent complexities that this library (by Vimeo themselves) makes way easier. Plus it’s only 1.8kb so I’d recommend it.

<script src="froogaloop.min.js"></script>

3. Create the player object

var iframe = document.getElementById('video');

// $f == Froogaloop
var player = $f(iframe);

We target the iframe by the id attribute we added. Then we create the player using the special froogaloop $f.

4. Bind events

All we have to do now is call methods on that player object to play and pause the video, so let’s call them when our play and pause buttons are clicked.

var playButton = document.getElementById("play-button");
playButton.addEventListener("click", function() {
  player.api("play");
});

var pauseButton = document.getElementById("pause-button");
pauseButton.addEventListener("click", function() {
  player.api("pause");
});

All Together Now

That’ll do it for Vimeo. Here’s a demo:


You can do much more with the APIs for both of these services. It can be pretty fun, just dive in!