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,
        );

 

Advertisements
Nginx, ubuntu, linux, apache, php, mysql

How To Install Linux, nginx, MySQL, PHP (LEMP) stack on Ubuntu 12.04

About Lemp

LEMP stack is a group of open source software to get web servers up and running. The acronym stands for Linux, nginx (pronounced Engine x), MySQL, and PHP. Since the server is already running Ubuntu, the linux part is taken care of. Here is how to install the rest.

Tutorial source – Digital Ocean

Setup

The steps in this tutorial require the user to have root privileges. You can see how to set that up in the Initial Server Setup Tutorial in steps 3 and 4.

Step One—Update Apt-Get

Throughout this tutorial we will be using apt-get as an installer for all the server programs. On May 8th, 2012, a serious php vulnerability was discovered, and it is important that we download all of the latest patched software to protect the virtual private server.

Let’s do a thorough update.

sudo apt-get update

Step Two—Install MySQL

MySQL is a powerful database management system used for organizing and retrieving data

To install MySQL, open terminal and type in these commands:

sudo apt-get install mysql-server php5-mysql

During the installation, MySQL will ask you to set a root password. If you miss the chance to set the password while the program is installing, it is very easy to set the password later from within the MySQL shell.

Once you have installed MySQL, we should activate it with this command:

sudo mysql_install_db

Finish up by running the MySQL set up script:

sudo /usr/bin/mysql_secure_installation

The prompt will ask you for your current root password.

Type it in.

Enter current password for root (enter for none): 
OK, successfully used password, moving on...

Then the prompt will ask you if you want to change the root password. Go ahead and choose N and move on to the next steps.

It’s easiest just to say Yes to all the options. At the end, MySQL will reload and implement the new changes.

By default, a MySQL installation has an anonymous user, allowing anyone
to log into MySQL without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] y                                            
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] y
... Success!

By default, MySQL comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] y
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] y
 ... Success!

Cleaning up...

Once you’re done with that you can finish up by installing PHP.

Step Three—Install nginx

Once MySQL is all set up, we can move on to installing nginx on the VPS.

echo "deb http://ppa.launchpad.net/nginx/stable/ubuntu $(lsb_release -sc) main" | sudo tee /etc/apt/sources.list.d/nginx-stable.list
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys C300EE8C
sudo apt-get update
sudo apt-get install nginx

nginx does not start on its own. To get nginx running, type:

sudo service nginx start

You can confirm that nginx has installed an your web server by directing your browser to your IP address.

You can run the following command to reveal your VPS’s IP address.

ifconfig eth0 | grep inet | awk '{ print $2 }'

Step Four—Install PHP

To install PHP-FPM, open terminal and type in these commands. We will configure the details of nginx and php details in the next step:

sudo apt-get install php5-fpm

Step Five—Configure php

We need to make one small change in the php configuration.Open up php.ini:

 sudo nano /etc/php5/fpm/php.ini

Find the line, cgi.fix_pathinfo=1, and change the 1 to 0.

cgi.fix_pathinfo=0

If this number is kept as 1, the php interpreter will do its best to process the file that is as near to the requested file as possible. This is a possible security risk. If this number is set to 0, conversely, the interpreter will only process the exact file path—a much safer alternative. Save and Exit. We need to make another small change in the php5-fpm configuration.Open up http://www.conf:

 sudo nano /etc/php5/fpm/pool.d/www.conf

Find the line, listen = 127.0.0.1:9000, and change the 127.0.0.1:9000 to /var/run/php5-fpm.sock.

listen = /var/run/php5-fpm.sock

Save and Exit.

Restart php-fpm:

sudo service php5-fpm restart

Step Six—Configure nginx

Open up the default virtual host file.

sudo nano /etc/nginx/sites-available/default

The configuration should include the changes below (the details of the changes are under the config information):

UPDATE: Newer Ubuntu versions create a directory called ‘html’ instead of ‘www’ by default. If /usr/share/nginx/www does not exist, it’s probably called html. Make sure you update your configuration appropriately.

 [...]
server {
        listen   80;
     

        root /usr/share/nginx/www;
        index index.php index.html index.htm;

        server_name example.com;

        location / {
                try_files $uri $uri/ /index.html;
        }

        error_page 404 /404.html;

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
              root /usr/share/nginx/www;
        }

        # pass the PHP scripts to FastCGI server listening on the php-fpm socket
        location ~ \.php$ {
                try_files $uri =404;
                fastcgi_pass unix:/var/run/php5-fpm.sock;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                include fastcgi_params;
                
        }

}
[...]

Here are the details of the changes:

  • Add index.php to the index line.
  • Change the server_name from local host to your domain name or IP address (replace the example.com in the configuration)
  • Change the correct lines in “location ~ \.php$ {“ section

Save and Exit

Step Seven—Create a php Info Page

We can quickly see all of the details of the new php configuration.

To set this up, first create a new file:

sudo nano /usr/share/nginx/www/info.php

Add in the following line:

<?php
phpinfo();
?>

Then Save and Exit.

Restart nginx

sudo service nginx restart

You can see the nginx and php-fpm configuration details by visiting http://youripaddress/info.php

Your LEMP stack is now set up and configured on your virtual private server.

Clean code

Writing cleaner conditional statements

Just a thought on using cleaner code while using a lot of nested if statements.

Clean code

Clean code

Ugly code

if(process_x()) {
    /* do a lot of other things */
    if(process_y()) {

         /* do a lot of other things */
         if(process_z()) {
              /* do a lot of other things */
              /* SUCCESS */
         }
         else {
              clean_all_processes();
         }
    }
    else {
         clean_all_processes();
    }
}
else {
    clean_all_processes();
}

Good looking code

do {

  if( !process_x() )
    { clean_all_processes();  break; }

  /* do a lot of other things */

  if( !process_y() )
    { clean_all_processes();  break; }

  /* do a lot of other things */

  if( !process_z() )
    { clean_all_processes();  break; }

  /* do a lot of other things */
  /* SUCCESS */

} while (0);

The use of goto is an alternative, the bad thing about this is you always need to define the label.

TimeAgo function in PHP

This can be used for comments and other from of communication to tell the time ago instead of the exact time which might not be correct to some one in another time zone.

The function only uses unix time stamp like the result of time();

function timeago($time) {
        $time = strtotime($time);
        $periods = array(L('second'), L('minute'), L('hour'), L('day'), L('week'), L('month'), L('year'), L('decade'));
        $periodsPlural = array(L('seconds'), L('minutes'), L('hours'), L('days'), L('weeks'), L('months'), L('years'), L('decades'));
        $lengths = array("60","60","24","7","4.35","12","10");

        $now = time();

        $difference     = $now - $time;
        $tense         = L('ago');

        for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++)
        {
            $difference /= $lengths[$j];
        }

        $difference = round($difference);

        if($difference != 1)
        {
            return "$difference $periodsPlural[$j] $tense";
        } else {
            return "$difference $periods[$j] $tense";
        }
    }

Needs a time() value, and it will tell you how many seconds/minutes/hours/days/years/decades ago.

PHP Dynamic page

How to create dynamic pages with php

This tutorial will show you how to create dynamic pages with php. As you know php is the best language to create dynamic website and today we are going to see how it’s done.

Step 1: Create files

First we need few separate pages so let’s go ahead and create few pages. First page we need is index.php that will be our main page, so create a page and name it index.php. After that we need to add some HTML to the page.

<html>
<head>
<title>My PHP Site</title>
</head>
<body>
<h1>Welcome to my PHP Site.</h1>
 <ul>
 <li>Products</li>
 <li>Blog</li>
 <li>About Us</li>
</ul>
</body>
</html>

This is going to be our main page that’s why we are putting our navigation here, it doesn’t look fancy because our main focus is PHP right now.

Add Links:

Now we need to add links to our navigation. As we have three items in our navigation so we will need three more pages for our website but first let’s add some links to our navigation items.

<ul>
 <li><a href="#">Products</a></li>
 <li><a href="#">Blog</a></li>
 <li><a href="#">About Us</a></li>
</ul>

For now we will not specify any path in our links, we will get back to it later. Now if you have done everything alright you will get a page like this:

Dynamic PHP pages

PHP Dynamic Page

Other pages:

Now that we are done with our main page, we want to create few other pages. So just create three pages and name them products.php , blog.php and about.php. After that we want to put some content in these pages, we don’t have to put all those HTML tags again. We will just have to put the content that we want to show on the website, so for product’s page put the following lines in the page.

<?php
echo "<h2>Products</h2>";
echo "This is our product page.<br/>";
echo "You should be able to see all of our products here.";
?>

Do same for other two pages. You can put in there whatever you like, just keep in mind one thing that you won’t have to put <html> tags again.

Step 2: Making Pages Dynamic

As we are done with our main page and we have created other pages, now its turn to make those pages dynamic. We will just have to change the url to get the requested page and after that use GET variable to catch the value and assign it to another variable. Then we can just print that variable and we will get all the content from other pages on our main page.

Add this php code on top of your main page:

<?php
 if(isset($_GET['page'])){
 $page = $_GET['page'];
 }
 else
 $page = NULL;
 ?>

So basically what we have done here is, we have checked if the value in GET is set or not and if it is set we have assigned the value in GET to page variable and if it is not set we have set page variable equal to NULL.
Secondly we need to add some code to our main page where we want to show the content of other pages. As we need to show the content of other pages after our navigation so put these line after closing ul tag.

<?php
 if(empty($page)){
 echo "This is our main page.";
 }
 else
 include($page);
 ?>

Here we are checking if the page variable is empty then show the content of main page and if the page variable is not empty then we will include page variable. Basically the page variable contains our page which we want to show on our main page, don’t worry it will all make sense in a minute.

Changing Links:

After our main page is all set the last thing we need to do is to change our link in the main page. So just make these changes in the links of main page.

<ul>
 <li><a href="index.php?page=products.php">Products</a></li>
 <li><a href="index.php?page=blog.php">Blog</a></li>
 <li><a href="index.php?page=about.php">About</a></li>
 </ul>

As you can see all these pages are referring to the index.php but here our concern is the part after the index.php that is the part after ?. After ? we are using a variable or you can say reference name ‘page’, you can use any name here but you will have to change the GET variable too. We are taking page equal to our required page.

After it’s all set you can try it and hopefully it will work.

Image Not Available

PHP Dynamic Page

Image Not Available

PHP Dynamic Page

Image Not Available

PHP Dynamic Page

Step 3: Improving Links

You can take it one step farther by modifying the code little bit and making your link more attractive instead of index.php?page=about.php. So what you need to do is add a line right after where you are assigning GET variable value to page in index page.

<?php
 if(isset($_GET['page'])){
 $page = $_GET['page'];
 $page .= '.php';  //Add this line here and you are all set.
 }
 else
 $page = NULL;
 ?>

Now last thing you want to do is to remove the .php extension from all the links and after that our links will become:

<ul>
 <li><a href="index.php?page=products">Products</a></li>
 <li><a href="index.php?page=blog">Blog</a></li>
 <li><a href="index.php?page=about">About</a></li>
 </ul>

Now when you will browse to any of these links it will not show .php and your link will look more lively like index.php?page=about. We are done and now you can play a little bit more if you want with your pages. Go ahead and try this and leave a comment if you get stuck anywhere or want to share something new.