Advertisement
  1. Code
  2. PHP
Code

How to Update your Twitter Status with CodeIgniter

by
Difficulty:IntermediateLanguages:

Hi, in this tutorial we will update our twitter status via the 'Twitter API' using CodeIgniter. I recommend following step by step, rather than glossing over the tutorial. Let's dig in!

Tutorial Details

  • Program: CodeIgniter PHP Framework
  • Version: 1.7.1
  • Difficulty: Advanced
  • Estimated Completion Time: 30 minutes

1. Configuring CodeIgniter

At first we need to edit some default settings within the CI config section.

Open the system/application/config/autoload.php and edit the following from:

to:

This will autoload the database. Next, open database.php and edit the database connection setting - the name of
your database, user and password. As name we will be using ci_twitter_api.

Now open config.php and change the base_url to your CI folder. My folder is called twitter_api.
In that folder is my system folder. So my base_url will be:

2. Filling the Database

Because we are going to work with a database, we will need some data to play with. Open phpmyadmin or your
favorite database management tool and create a new database called ci_twitter_api. Now we will set up a
new table using the following SQL query, but attention, use YOUR twitter username and password credentials.

Click the OK button on the right side and the query should be processed. Now your structure for the table
accounts should look similar to the image below.

3. Building the Model

Go to system/application/models and create a new file called twitter_model.php.

First, we'll declare two global variables at the top.

So $accounts_table refers to the table we created just before, and $update_url is the url we will be using
to update our status. If Twitter changes their update URL, you only need to edit it one time here instead of every time its used in the code.

Now we will create our first method which will simply return the active user account stored in the database,
based on the row active and value 1. I have added this because some people have two or more Twitter
accounts.

We are simply using active records
to retrieve the active account and return the affected row.

Next step, we are going to build the main method, the update method. This will use our
username, password and of course the message we want to send and update our status on Twitter. Apart from that,
it will interpret the HTTP_CODE which is returned by Twitter for telling us if the status was updated
successfully or not.

At first view the code above may look a bit complicated but it's not that hard to understand. The most important part is
that we use cURL to communicate with Twitter. It's a really great
library which allows us to send and receiveHTTP POST data from Twitter.

Now then curl_init initializes a cURL session and takes the URL as a parameter - in our case the status update
URL from the Twitter API.

With curl_setopt we set some necessary options for the cURL transfer.

  • CURLOPT_POST: We set this to '1' to use HTTP POST, which is the same as used in HTML forms.
  • CURLOPT_POSTFIELDS: This options aceepts the POST Data that we want to send. In our case
    'status=' and our message. We need to urlencode the message to be able to use special
    characters like '%&/" .
  • CURLOPT_RETURNTRANSFER: Its important for us to set this to '1' because it will return the transfer
    as a string. That string will later tell us if the status was updated successfully or not.
  • CURLOPT_USERPWD: This option is for authentication. It simply takes our twitter username and password
    in the format username:password.

In this part we are executing the transfer with curl_exec() and retrieving the returned HTTP_CODE
using curl_getinfo(CURLINFO_HTTP_CODE). This HTTP_CODE tells us if the status update was completed or not.
Code '200' means it worked and the update was done. You can view a complete list of HTTP status codes
here.

If we get '200' returned by Twitter, we send a query to our database which updates our last_message row, and finally
we return TRUE. If 200 is not returned, we simply return FALSE.

To finish our twitter_model we will create one last method which will get the last message we sent. We need
this method because we will display our most recent message in a view.

This method is pretty simple. It selects the last_message row from our active account and returns it
converted with htmlspecialchars to HTML entities.
Our twitter_model.php now looks like this:

4. Building the Controller

Now go to system/application/controllers and create a new file called twitter.php.
Let's add some lines:

This is a simple CI constructor which loads our twitter_model. So it will be available to us within the whole controller.
Now comes the index() method.

We are passing information like some text, our last message and the username of the active user to the $data array.
Thanks to our twitter_model it's a cinch to grab the last message and the active username. At least we are loading some
views which we will create after we finish our controller. Let's build the update method.

This may be confusing again but we will go through it part by part.

With $this->input->post('submit') we check if the form was submitted - which we will create later in our main view
file. After that, we load the form_validation library because we want to ensure that certain inputs require some rules,
like a minimum and maximum length of 5 and 140 characters. Additionally we are trimming off the whitespace with trim and
setting the field as required because we don't need an empty message. The function set_rules takes, as the first parameter,
the name of the from field, our case message (which will be created soon in the view) and as second parameter a human
the name for this field, which will be inserted into the error message ( will be done in the view file ).

We call $this->form_validation->run(), which can return TRUE or FALSE. If a rule we set was broken it
will return FALSE and we simply call our index() method. In the view files called by the index() method the
error messages will be displayed after we have created our views.

Thanks to our twitter_model, again it's so easy to retrieve the username and the password of the current active user.
We could also do $username = $this->twitter_model->getActiveAccount()->username but I think for this tutorial this is
a little bit easier to understand.

Using $this->twitter_model->update_status() we call the method that will "talk" to Twitter. It tells Twitter our
username, password and our message. If the status was updated successfully, we redirect, using redirect() from the url helper.

If something was wrong, we set an error message and load some view files, which will be created in the next step :).
The Controller looks now like this:

5. Creating the Views

Now we will create our view files. Go to system/application/views and create the following files:

  • header.php
  • footer.php
  • index.php
  • error.php

The header.php will contain the basic html meta information, our CSS link, and the opening tags of our main divs,
#wrapper and #main.

We are using base_url() which we configured to reference our CSS file, which will be created in the next step.

The footer.php simply contains our closing tags.

The index.php is where the party goes.

All variables used here are passed through the index() method from our controller. In addition to that,
we are using the form helper to create a simple html form. Remember, I told you the error handling for the
message field will be done here; form_error('message') is doing that magic.

Below the form we are displaying the last message sent by the active user's account.

Finally the error.php will be used for a custom error file in case the status update was unsuccessful.

6. Adding some CSS

To make it a bit prettier, we will add some CSS. Go to system/
and create the folder css. Inside of that folder create a file called style.css and insert
the following code.

I am using Eric Meyers CSS reset to neutralize the view on all browsers. Your application should now likebthe image below.

The Big Finale

Let's test our fresh application. We'll drop a message and press the update button!

After the update was made:

Lets take a look at Twitter :)

if we are violating a form validation rule by trying to send an empty message:

Conclusion

I really hope that I helped you a little bit with learning CodeIgniter and how to use the great Twitter API! Would you have done anything differently? If so, let us know!

Advertisement
Advertisement
Looking for something to help kick start your next project?

Envato Market has a range of items for sale to help get you started.