1. Code
  2. PHP
  3. CodeIgniter

How to Update your Twitter Status with CodeIgniter

Scroll to top
12 min read

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:

1
$autoload['libraries'] = array('');

to:

1
$autoload['libraries'] = array('database');

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:

1
$config['base_url']	= "http://localhost/ci/twitter_api";

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.

1
CREATE TABLE IF NOT EXISTS `accounts` (
2
     `id` int(11) NOT NULL AUTO_INCREMENT,
3
     `username` varchar(120) NOT NULL,
4
     `password` varchar(32) NOT NULL,
5
     `active` int(11) NOT NULL,
6
     `last_message` varchar(140) NOT NULL,
7
     PRIMARY KEY (`id`)
8
   ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
9
   
10
   INSERT INTO `accounts` (`id`, `username`, `password`, `active`, `last_message`) VALUES
11
   (1, '<b>YOUR USERNAME</b>', '<b>YOUR PASSWORD</b>', 1, 'No message sent.');

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.

1
var $accounts_table = 'accounts';
2
var $update_url = 'http://twitter.com/statuses/update.xml';

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.

1
 class Twitter_model extends Model {
2
3
    // get the active twitter account from the database, by row active = 1

4
    function getActiveAccount()
5
    {
6
        return $this->db->get_where($this->accounts_table, array('active' => '1'))->row();	
7
    }

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.

1
// update twitter status and last message on success

2
function update_status($username, $password, $message)
3
{
4
	$ch = curl_init($this->update_url);
5
6
	curl_setopt($ch, CURLOPT_POST, 1);
7
	curl_setopt($ch, CURLOPT_POSTFIELDS, 'status='.urlencode($message));
8
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
9
	curl_setopt($ch, CURLOPT_USERPWD, $username . ':' . $password);
10
	
11
	curl_exec($ch);
12
	
13
	$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
14
	
15
	// if we were successfull we need to update our last_message

16
	if ($httpcode == '200')
17
	{
18
		$this->db->where('active', '1');
19
		$this->db->update($this->accounts_table, array('last_message' => $message));
20
		
21
		return TRUE;	
22
	}
23
	
24
	else
25
	{
26
		return FALSE;	
27
	}
28
}

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.
1
curl_exec($ch);
2
3
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
4
5
// if we were successfull we need to update our last_message

6
if ($httpcode == '200')
7
{
8
	$this->db->where('active', '1');
9
	$this->db->update($this->accounts_table, array('last_message' => $message));
10
	
11
	return TRUE;	
12
}
13
14
else
15
{
16
	return FALSE;	
17
}

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.

1
// get the last_message, by row active = 1

2
function getLastMessage()
3
{
4
	$this->db->select('last_message');
5
	$last_message =  $this->db->get_where($this->accounts_table, array('active' => '1'))->row()->last_message;
6
	
7
	return htmlspecialchars($last_message);
8
}

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:

1
	class Twitter_model extends Model {
2
	
3
	var $accounts_table = 'accounts';
4
	var $update_url = 'http://twitter.com/statuses/update.xml';
5
	
6
	// get the active twitter account from the database, by row active = 1

7
	function getActiveAccount()
8
	{
9
		return $this->db->get_where($this->accounts_table, array('active' => '1'))->row();	
10
	}
11
	
12
	// update twitter status and last message on success

13
	function update_status($username, $password, $message)
14
	{
15
		$ch = curl_init($this->update_url);
16
17
		curl_setopt($ch, CURLOPT_POST, 1);
18
		curl_setopt($ch, CURLOPT_POSTFIELDS, 'status='.urlencode($message));
19
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
20
		curl_setopt($ch, CURLOPT_USERPWD, $username . ':' . $password);
21
		
22
		curl_exec($ch);
23
		
24
		$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
25
		
26
		// if we were successfull we need to update our last_message

27
		if ($httpcode == '200')
28
		{
29
			$this->db->where('active', '1');
30
			$this->db->update($this->accounts_table, array('last_message' => $message));
31
			
32
			return TRUE;	
33
		}
34
		
35
		else
36
		{
37
			return FALSE;	
38
		}
39
	}
40
	
41
	// get the last_message, by row active = 1

42
	function getLastMessage()
43
	{
44
		$this->db->select('last_message');
45
		$last_message =  $this->db->get_where($this->accounts_table, array('active' => '1'))->row()->last_message;
46
		
47
		return htmlspecialchars($last_message);
48
	}
49
}

4. Building the Controller

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

1
class Twitter extends Controller {
2
3
function Twitter()
4
{
5
	parent::Controller();
6
	
7
	$this->load->model('twitter_model');
8
}

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.

1
function index()
2
{
3
	$data['heading'] = 'Hi, send a tweet!';
4
	$data['last_message'] = $this->twitter_model->getLastMessage();
5
	$data['active_user'] = $this->twitter_model->getActiveAccount()->username;
6
	
7
	$this->load->view('header', $data);
8
	$this->load->view('index');
9
	$this->load->view('footer');
10
}

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.

1
// updating our status on twitter ( new message )

2
function update()
3
{		
4
	if ($this->input->post('submit'))
5
	{
6
		$this->load->library('form_validation');
7
		$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
8
		$this->form_validation->set_rules('message', 'Message', 'trim|required|min_length[5]|max_length[140]');
9
		
10
		if ($this->form_validation->run() == FALSE)
11
		{
12
			$this->index();
13
		}
14
		
15
		else
16
		{
17
			$message = $this->input->post('message');
18
			
19
			// get useraccount data

20
			$account = $this->twitter_model->getActiveAccount();
21
			$username = $account->username;
22
			$password = $account->password;
23
			
24
			// send a tweet

25
			if ($this->twitter_model->update_status($username, $password, $message))
26
			{
27
				redirect('twitter');	
28
			}
29
			
30
			else
31
			{
32
				$data['error'] = 'There was an error while updating your status';
33
				
34
				$this->load->view('header', $data);
35
				$this->load->view('error');
36
				$this->load->view('footer');
37
			}
38
		}
39
	}

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

1
if ($this->input->post('submit'))
2
	{
3
		$this->load->library('form_validation');
4
		$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
5
		$this->form_validation->set_rules('message', 'Message', 'trim|required|min_length[5]|max_length[140]');
6
		
7
		if ($this->form_validation->run() == FALSE)
8
		{
9
			$this->index();
10
		}

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.

1
else
2
   {
3
       $message = $this->input->post('message');
4
       
5
       // get useraccount data

6
       $account = $this->twitter_model->getActiveAccount();
7
       $username = $account->username;
8
       $password = $account->password;
9
       
10
       // send a tweet

11
       if ($this->twitter_model->update_status($username, $password, $message))
12
       {
13
           redirect('twitter');	
14
       }
15
       
16
       else
17
       {
18
           $data['error'] = 'There was an error while updating your status';
19
           
20
           $this->load->view('header', $data);
21
           $this->load->view('error');
22
           $this->load->view('footer');
23
       }
24
   }

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:

1
	class Twitter extends Controller {
2
3
	function Twitter()
4
	{
5
		parent::Controller();
6
		
7
		$this->load->model('twitter_model');
8
	}
9
	
10
	function index()
11
	{
12
		$data['heading'] = 'Hi, send a tweet!';
13
		$data['last_message'] = $this->twitter_model->getLastMessage();
14
		$data['active_user'] = $this->twitter_model->getActiveAccount()->username;
15
		
16
		$this->load->view('header', $data);
17
		$this->load->view('index');
18
		$this->load->view('footer');
19
	}
20
	
21
	// updating our status on twitter ( new message )

22
	function update()
23
	{		
24
		if ($this->input->post('submit'))
25
		{
26
			$this->load->library('form_validation');
27
			$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
28
			$this->form_validation->set_rules('message', 'Message', 'trim|required|min_length[5]|max_length[140]');
29
			
30
			if ($this->form_validation->run() == FALSE)
31
			{
32
				$this->index();
33
			}
34
			
35
			else
36
			{
37
				$message = $this->input->post('message');
38
				
39
				// get useraccount data

40
				$account = $this->twitter_model->getActiveAccount();
41
				$username = $account->username;
42
				$password = $account->password;
43
				
44
				// send a tweet

45
				if ($this->twitter_model->update_status($username, $password, $message))
46
				{
47
					redirect('twitter');	
48
				}
49
				
50
				else
51
				{
52
					$data['error'] = 'There was an error while updating your status';
53
					
54
					$this->load->view('header', $data);
55
					$this->load->view('error');
56
					$this->load->view('footer');
57
				}
58
			}
59
		}
60
		
61
		else
62
		{
63
			redirect('twitter');
64
		}
65
	}
66
}

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.

1
    <!DOCTYPE html>
2
    <html>
3
    <head>
4
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5
    <link media="screen" rel="Stylesheet" type="text/css" href="<?php echo base_url(); ?>css/style.css" />
6
    <title>Using the Twitter API with CodeIgniter</title>
7
    </head>
8
    
9
    <body>
10
    
11
    <div id="wrapper">
12
    
13
    <div id="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.

1
	</div><!--end main-->
2
3
    </div><!--end wrapper-->
4
    
5
    </body>
6
    </html>

The index.php is where the party goes.

1
	<h3>
2
	<?php echo $heading; ?>
3
    <span>
4
    	( account: <?php echo anchor('http://twitter.com/' . $active_user, $active_user); ?> )
5
    </span>
6
    </h3>
7
    
8
    
9
    <?php echo form_error('message'); ?>
10
    
11
    <?php echo form_open('twitter/update', array('id' => 'update_form')); ?>
12
    <?php echo form_input(array('name' => 'message', 'maxlength' => '140')); ?>
13
    <?php echo form_submit('submit', 'update'); ?>
14
    <?php echo form_close(); ?>
15
    
16
    <div id="last_message">
17
        <fieldset>
18
            <legend>Last <span>sent by <b><?php echo $active_user ?></b></span></legend>
19
            <p><?php echo $last_message; ?></p>
20
        </fieldset>
21
    </div><!--end last_message-->

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.

1
	<h3><?php echo $error; ?></h3>
2
3
     <?php echo anchor('twitter', 'Go back and try again'); ?>

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.

1
    /* Reset CSS */
2
    
3
    html, body, div, span, object, h1, h2, h3, h4, h5, h6, p, blockquote, pre,
4
    a, address, code, img, 
5
    small, strong, dl, dt, dd, ol, ul, li,
6
    fieldset, form, label {
7
        margin: 0;
8
        padding: 0;
9
        border: 0;
10
        outline: 0;
11
        font-size: 100%;
12
        vertical-align: baseline;
13
        background: transparent;
14
    }
15
    
16
    body {
17
    	line-height: 1.5;
18
        font-family:Arial, sans-serif;
19
        margin:0;
20
    }
21
    ol, ul, li {
22
        list-style: none;
23
        list-style-type:none;
24
    }
25
    
26
    .clear { clear:both; }
27
    
28
    /* DEFAULTS */
29
        
30
    h3 {
31
        color:#35CCFF;
32
        font-size:20px;
33
    }
34
35
    /* CUSTOM */
36
        
37
    #wrapper {
38
        width:900px;
39
        margin:0 auto;
40
    }
41
    
42
    /* main */
43
    
44
    #main {
45
        margin-top:50px;
46
    }
47
    
48
    #main h3 span {
49
        font-size:14px;	
50
        color:#cccccc;	
51
    }
52
    
53
    #main h3 a {
54
        color:#cccccc;	
55
    }
56
    
57
    /* form */
58
    
59
    #update_form input {
60
        width:888px;
61
        padding:5px;
62
        border:1px solid #d3d3d3;
63
        display:block;
64
    }
65
    
66
    #update_form input[type="submit"] {
67
        width:auto;
68
        margin-top:10px;
69
        background-color:#000000;;
70
        border:none;
71
        color:white;
72
        font-size:12px;
73
        font-weight:bold;
74
        cursor:pointer;
75
        padding:3px;
76
    }
77
    
78
    div.error {
79
        display:block;
80
        background-color:#FB8A8A;
81
        border:1px solid #FF3B3B;
82
        padding:5px;
83
        color:#ffffff;
84
        width:50%;
85
        margin-bottom:30px;
86
        font-weight:bold;
87
        margin:0 auto 10px auto;
88
        text-align:center;
89
    }
90
    
91
    /* last message */
92
    
93
    #last_message fieldset {
94
        border:1px dashed #d3d3d3;
95
        padding:5px;
96
        margin-top:30px;
97
    }
98
    
99
    #last_message fieldset p {
100
        padding:5px;
101
        font-size:18px;
102
        font-weight:normal;
103
    }
104
    
105
    #last_message legend span {
106
        font-size:12px;
107
    }

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!

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.