Archive for the ‘Web’ Category

Using the keyword “this” in PHP

Wednesday, October 21st, 2009

You may have come across number of functions and variables inside a class and perhaps you don’t even know how they’re called or invoked. These functions and variables that belong to a class are called as properties and methods, or simply members, of this class.

In PHP, the keyword “$this” is used as a self reference of a class and you can use it for calling and using these properties and methods as shown in the example bellow.

Create a file ClassOne.php with code bellow:
<?php

class ClassOne
{
    // this is a property of this class
    public $propertyOne;

    // When the ClassOne is instantiated, the first method called is
    // its constructor, which also is a method of the class
    public function __construct($argumentOne)
    {
        // this key word used here to assign
        // the argument to the class
        $this->propertyOne = $argumentOne;
    }

    // this is a method of the class
    function methodOne()
    {
        //this keyword also used here to use  the value of variable $var1
        return 'Method one print value for its '
             . ' property $propertyOne: ' . $this->propertyOne;
    }
}

In this class, we are also using the visibility declarations (public), which means whether the members are accessible on a subclass – we will discuss it later – or instance.
Another thing you must be curious about is the use of ‘->’. This is an object pointer and, on PHP, it’s used for accessing members inside an object.

Now, let’s test your class! Create another file, called use.php with the following code:
<?php

// include your class file
require_once 'ClassOne.php';

// Create an instance of your class
$classOneInstance = new ClassOne('Hello');

// And test it
print $classOneInstance->propertyOne . '<br />';
print $classOneInstance->methodOne();

- Note that in both files we’re not using the enclosing PHP tags (?>). Once they have only PHP code, it’s not needed and it’s also a good practice to avoid them on pure PHP files.

Zend Framework – Sourcebits Contribution Team

Wednesday, October 21st, 2009

Sourcebits is investing efforts for making one of the best PHP frameworks even better. With a whole team of talented and skilled developers, we’re contributing to the framework using the best proven components we have developed based on our experience using the Zend Framework on our projects.

You can check out the proposals we have already submmitted for review here:
* Zend Calendar.
* Zend Template.

Hope you’ll enjoy! ;)

No IE6 support on new W3C website?

Wednesday, October 21st, 2009

W3.org is overhauling its website in order to make it more user-friendly and quiet people who used to wonder (including me) why the administrator body of web have such dull, flat, unorganized and old fashioned website?

The new website looks more attractive and organized. 10 minutes tour of new website can be found here. In contrast with the previous version, this new website uses rich content presentation, including JavaScript.

The website uses jQuery 1.3.2, a very known and popular JavaScript library, instead of pure JavaScript. This is very good news and a big leap towards streamlining the use of JavaScript frameworks, specially in case of jQuery. In addition of core jQuery framework, beta.w3.org also uses jQuery plugins (e.g.: http://malsup.com/jquery/cycle/), to enhance the user experience.

The biggest news of the day is w3.org beta website doesn’t render correctly in IE6. It’s supposed to be a strong argument for web developers in order to inspire and take initiative towards to stop exclusive coding to render their websites correctly in IE6.

FLOW3 is arriving

Wednesday, October 21st, 2009

Not yet released, FLOW3 starts making noises on the mass: what’s TYPO3 up to?

As a result of the already proven TYPO3 CMS, the upcoming 5th version of the system is bringing a solid PHP framework, which can be used apart from the whole system for developing applications of any kind.

The FLOW3 subsite stats, against what’s commonly seen out there, FLOW3 is not a pick’n’mix store of motley components. It’s a framework which helps you with the infrastructure of your application. Object Lifecycle Management, Package Management, Resource Management and Security are on his home field. Real business logic is left over to third-party packages.

All the most common features we can find in other PHP frameworks are going to be provided by FLOW3, like MVC architecture, Validation, Filters, Persistence Object Manager and much more.

Next week, I’ll post a getting started with a simple application and provide my personal review of this framework, which – OMHO – is going to rock!

Dual form processing

Wednesday, October 21st, 2009

Recently, a client of mine wanted a single web form, residing on the localhost to submit the form contents to a database in the localhost, and as well as to a web server simultaneously. Although this sounds like an unnecessary duplication of data, my client wanted some of the form data to be stored on the localhost for the intranet applications to use. Achieving this functionality would have been a piece of cake, if we were not handicapped by the unavailability of cross-domain AJAX. For those of us familiar with AJAX, we know that we cannot send an AJAX request to a remote server due to security reasons – atleast not in a reliable, hack-less way.

So, instead of looking for a pure AJAX solution, I decided to implement this functionality by using a combination of AJAX (for the localhost) and a traditional PHP POST request (for the web server). The trick here is to execute the AJAX call before the form is submitted – by catching the form submission event using JavaScript. Once the AJAX call is successful, we allow the default form submission to take place. In case there is an error with our AJAX call, we should stop the propogation of the traditional form submission too.

Ok, so let’s start off with a simple example – a no-frills form with a few fields.


<form method="post" id="webform" action="http://www.example.com/path/to/PHPscript.php">

<label for="firstname">first name:</label>
<input type="text" name="firstname" id="firstname" value="" />

<label for="lastname">last name:</label>
<input type="text" name="lastname" id="lastname" value="" />

<label for="email" id="l_email">email address:</label>
<input type="text" name="email" id="email" value="" />

<input type="submit" name="Submit" id="submit_butt" value="Submit" />
<input type="reset" />

</form>

When the above form is submitted as it is, the form contents will be sent to the PHP script in the webserver. As I mentioned earlier, what we need to do now is “catch” this form submission event and insert our AJAX call before that. Let’s see how we can do that now. We will be using jQuery for our JavaScript needs.


$(document).ready(function(){
$("#webform").submit( function()
{
var success = -1;

$.post("localScript.php",
{
firstname: $("#firstname").val(),
lastname: $("#lastname").val(),
email: $("#email").val()
},

function(response){

if(response.status == "0")
success = false;
else
success = true;

}, "json");

var d = new Date();
var t = d.getSeconds();

while(success==-1)
{
var d = new Date();
if(d.getSeconds() - t > 4)
{
success = false;
break;
}
}

return success;
});
});

We set-up an event handler using jQuery, which fires whenever the form is submitted. We then make an AJAX call to the localhost to submit the form contents. We have a callback function which checks the status of the AJAX call. In case, any error occurs on the localhost, an error code can be returned (in our case, the status value will be 0) and we have to stop the form submission by returning “false” from the event handler function. This will stop the default action of the submit button, i.e. it will prevent the HTTP form submission.

This is achieved using a hack. Since the script will not wait for the callback function to return, the next statement, i.e. the “return” statement will be executed immediately after the $.post() call is made to the server. However, we cannot return from the function without knowing whether the operation on the backend succeeded or not. Since, JavaScript does not natively have any sleep()-like function, we have to force our script to get into a blocked state using a while() loop. We then manually terminate the while loop if we did not hear back from the server within a “few” seconds. In our example we have defined the timeout to be 4 seconds. In case we don’t hear from the server within this time, we will terminate the form submission by returning a “false”. This elaborate hack is required to ensure that we do not proceed to the next stage without knowing what happened to the data we submitted to the localhost.

If everything goes well in the localhost, the contents of the form will be processed and stored in the localhost database by the PHP script we have called using AJAX. The submit event handler will then return “true”. This would in turn cause the form to be submitted to the PHP script on the remote server, as defined in the action attribute of the <form> tag. Once the form is submitted, the browser requests, and loads this PHP script. The PHP scripts recieves the form contents as POST variables and saves them (by perhaps, storing them in a database).

We are not done yet, though. We still have to send the user back to a page on the localhost once the PHP script has finished processing and storing the form contents. We do that by:


$redirect_url = "http://localhost/path/to/some/page";
header( 'Location: ' . $redirect_url );
exit;

It is important that the header() is called before any actual output is sent to the browser. For example, you should not have any echo statement, or raw HTML output before calling the header().

That’s about it! Now we are really done! In most cases, you will notice that this entire process is so slick that your user would hardly notice the redirection from the page on the webserver to the page on the localhost! I have put together a barebones HTML page containing the code fragments above, which you can download for your reference and use from here.

Light weight alternatives to Apache

Wednesday, October 21st, 2009

When it comes to choosing a Linux web server, Apache, as we all know, is almost a de facto standard. There is even a chance that your web host does not even offer (or worse, know of) an alternative web server. So, it’s not a big surprise that many developers don’t know too much about what other alternatives are available to them.

There is of course no denying that Apache is indeed an old war horse, and an extremely robust and mature one at that. But, even as stable as Apache is, it has one main drawback – it occupies a large memory footprint due to its request-per-process model, and is therefore mediocre at handling multiple concurrent requests when you have a limited RAM. This can be a problem when you are starting out small, with a rented 256 MB VPS for your application. Even if you are a big player, light weight Apache alternatives can help increase the throughput of your servers. Youtube, for instance, was using Lighttpd, a light-weight web server to serve millions of videos everyday (prior to their acquisition by Google).

Ok enough digressing, let’s now take a look at some of the open source alternatives to Apache.

Lighttpd

Lighttpd, pronounced as Lighty, is a single threaded web server optimized for a large number of keep-alive connections, which is often a requirement for high traffic web applications. It was originally developed by the German programmer Jan Kneschke to solve the C10k problem (handle 10,000 parallel connections using a single server). Apart from Youtube as I have already mentioned, Wikipedia, Meebo and Sourceforge all use Lighttpd. Lighttpd is rich with features, and offers mod_rewrite (URL rewriting), FastCGI support, HTTP compression, amongst many other features. I was able to install and configure Lighttpd in a few minutes, and it is extremely light-weight (less than 1MB). I was able to get PHP/MySQL running in a couple of minutes, using the FastCGI interface.

One drawback, which I have seen repeatedly mentioned in many forums and blogs on the web (I could not verify these claims with my own tests), is that Lighttpd seems to suffer from memory leaks – which often required scheduled server restarts.

Nginx

Nginx, pronounced as Engine-X, is a web server originating from Russia, and is written by Igor Sysoev. Unlike Lighttpd, Nginx is not a single threaded webserver (it instead uses a single master process which delegates work to a small number of worker processes), but is another popular light weight web server alternative. It is supported by more than 20% of Russian virtual hosts, and is gaining lots of attention these days in other parts of the world too.

Nginx is excellent at serving static files and also supports reverse proxying. Like Lighttpd, I was able to get Nginx up and running in a few minutes. However, it does not come up with default FastCGI support – so getting PHP/MySQL working was a little tricky. It involves spawning a FastCGI process manually. I found this tutorial helpful.

Erlang based alternatives

Erlang is a concurrent programming language designed by Ericsson to support distributed, soft real time applications, which has been opensourced since 1998. I definitely want to write more about how scalable Erlang is, but this is not the article for that. So, let’s just say that Erlang is tailor-made for high demand applications which need to handle multiple concurrent connections – like a web server.

YAWS (Yet Another Web Server) and Mochiweb are two Erlang based web servers which I found to be highly scalable and light-weight.

A load test conducted matching Yaws against Apache found that Apache failed at 4,000 concurrent connections, while Yaws continued functioning with over 80,000 concurrent connections (source). I did have some trouble installing and configuring YAWS though. The documentation is scarce, to say the least.

Mochiweb is actually an Erlang library for building your own light-weight HTTP server. Don’t be put off by that statement! A simple server can be built with just a few lines of code. I installed and tested Mochiweb too, and I found it pretty easy. If you are interested, here is a tutorial which I found helpful.

So should you ditch Apache?

This decision depends on a number of factors. Like I have already stated, if you want to make the best out of the limited resources you have, then a light-weight web server is definitely advantageous. However, from my experience with playing with the above alternatives, if you do decide to go with one of them, you should be prepared to roughen it out. Poor documentation and support (the mailing lists and forums are generally helpful, but you can never completely rely on them when you are suddenly facing an issue in a production environment) could end up making things difficult for you. Don’t get me wrong, I am not saying that these servers are not production-ready yet (they are pretty stable), but there is always an off-chance you might just hit upon some snag. In that case, you probably have to roughen it out.

A reasonable choice would be to front Apache with one of these light weight web servers. In effect, you can use them for load balancing. Using reverse-proxying, you can handle the static files (like CSS and images) using a light weight web server, and route the dynamic requests to Apache.

So, in future, I hope you will consider an Apache alternative, should your needs be better satisfied by a light-er web server. If you have experience using any of the above alternatives, do share your views in the comments!

Avoiding long polling

Wednesday, October 21st, 2009

Right from Twitter to Google Wave, real time information streaming via the browser seems to be the most "happening" thing on the web arena currently. However, feeding real time information as and when it is available to an user using your web application is not as straight forward as it is on a desktop environment. HTTP is a stateless protocol which does not currently support a two way communication link between the server and the user’s computer via the browser.

The simplest way to simulate real time streaming of information is to poll the server every N seconds, and to display the information (if any). The number N will determine how real time the resulting stream of updates will look to a viewer. This model is simply called, polling. Now, polling is bad because it repeatedly connects and disconnects to the server, which when scaled across thousands of users, cause severe strain on your server. This problem becomes even more apparent in cases when the poller returns with empty data most of the times.

The jQuery snippet below polls the server every 3 seconds for new information and displays it in a simple alert box.

function callComplete(response) {
	alert("Response received is: "+response);
};

function connect() {
	// when the call completes, callComplete() will be called along with
	// the response returned
	$.post('/path/to/script.php', {}, callComplete, 'json');
};

$(document).ready( function() {
	setInterval(connect,3000);
}

Long polling

This technique is an optimisation of the traditional polling method. In long polling, once the client makes a connection with the server (via JavaScript), the server waits for the data requested by the client to become available. If it’s not immediately available, the server (being a PHP script for example) loops and sleeps. When the data is available, the server returns the data to the client and the connection closes. When this happens, the client again reconnects with the server (in the callback function of your original AJAX request).

This method is definitely an improvement over mindless polling, as we will avoid repeatedly opening and closing connections when data is not available for long periods of time. However, it is important to be aware of the server side technical limitations of long polling. Since connections might be kept alive for long durations of time, your web server must be capable of handling such large numbers of simultaneous connections. We talked about how certain light weight webservers outperformed Apache in this particular area in the last article.

Let’s look at a very simple jQuery/PHP long polling example:

function callComplete(response) {
	alert("Response received is: "+response);
	// reconnect to the server
	connect();
};

function connect() {
	// when the call completes, callComplete() will be called along with
	// the response returned
	$.post('/path/to/script.php', {}, callComplete, 'json');
};

$(document).ready( function() {
	connect();
}

In the PHP end, we do:

while(1) {

	$data = "some data fetched from the DB";

	// if we have new data, return it to the client
	if(!empty($data)) {
		echo json_encode($data);
		break;
	}

	sleep(3000);	// we sleep for 3s and check again for data
}

COMET streaming

COMET is a generic term that refers to the use a persistent HTTP connection for the web server to "push" data to the client as and when it arrives. If you have ever wondered how Gmail is able to notify you of a new email message seconds after it is sent, this is what they use to push the new email notifications to the front end.

However, as often is the case with JavaScript, the cross browser compatibility issues mean that a host of methods (targeting different browsers) are used to implement such an interaction. The upside is that these methods rely purely on JavaScript, and hence not dependent on any specific client side plugin. A detailed exploration of these different methods and their caveats is beyond the scope of this article, but let’s get a quick overview of these methods.

Hidden iframe technique: A hidden iframe html element is embedded onto the page, which points to the URL on the server which handles the persistent connection. The server will then push the data as it arrives to the iframe, using <script> tags. This content is then channeled to the parent window using JavaScript. This method is based on the fact that many browsers evaluate JavaScript chunks as they are received, even if the complete page has not finished loading yet. However this method is prone to cause the "loading" icon or status bar message to appear all the time (since we are using a persistent HTTP connection, the browsers tend to believe that the page is yet to finish loading fully).

XMLHttpRequest using Interactive readyState: This method is targetted towards Firefox, Safari and Chrome, which support the interactive readyState property of the XHR object, and fires events every time a chunk of data is received from the server.

Server-Sent events: This is a feature (from the WHATWG Web Applications 1.0 specification) supported by Opera since v9, using which we can push events from the server directly to the visitor’s browser. Refer to this article on how it’s used.

As you can see, it’s quite a mouthful, and hence implementing COMET streaming which works uniformly across all major browsers is not a task for the faint hearted (not forgetting that the webserver must also be able to handle a large number of persistent connection). The good news is that quite a lot of the hard work has already been done for you. There are various opensource COMET servers and client libraries which you can use to deploy a COMET application pretty safely. Here are a few of them for your exploration:

Orbited: "Orbited is an HTTP daemon that is optimized for long-lasting comet connections. Orbited allows you to write real-time web applications, such as a chat room or instant messaging client, without using any external plugins like Flash or Java. "

Cometd: "Cometd is a scalable HTTP-based event routing bus that uses a Ajax Push technology pattern known as Comet."

Meteor: "Meteor is an open source HTTP server, designed to offer developers a simple means of integrating streaming data into web applications without the need for page refreshes."

Comet Pi: This is a standalone JavaScript library which you can use to handle the various cross browser issues that COMET causes. You can use pi.comet with any serverside language.

Creating an inline contact form

Wednesday, October 21st, 2009

Customer feedback is arguably one of the most critical factors determining the success of a product over a period of time. Hence, it’s not surprising that many websites have some form of contact form or another to encourage users to write back to them. Most of these “contact” pages tend to be on a separate page which is usually part of the navigation or is linked to with phrases like “we encourage your feedback” or “do get in touch with us”, etc.

However, I have often noticed that many people (unless they genuinely needed help), either back away from submitting their comments (when they are confronted by a large textarea on the contact page), or simply move away from the site as the contact page loads.

Today, let’s spice things up a bit by using jQuery to load a lightweight inline contact form. So, instead of loading a separate contact form page when the “contact us” link is clicked, we will just have a small textarea opens up dynamically right next to the link – so that the user can type his feedback and it can be submitted rightaway using AJAX. Our main aim here is to encourage more users to provide feedback and although I don’t have actual data to prove whether an inline form will be any more helpful, I have used it in a couple of places, and it did appear to bring in more casual feedback about the site, features etc. Ok, let’s get started. Here is the demo of how it will all look in the end.

Okay, first let’s have a hypothetical page in which we want to make use of the inline contact form. The call of action, is obviously the “We would love to hear your feedback” link, which has the id “a_inline_form”. Initially, this hyperlink will simply point to the default contact form page. We will have the inline form in a DIV with id “inline_form”, which will be hidden initially.

#inline_form {
		/* keep the inline form hidden initially */
		display: none;

		position: relative;
		padding: 10px;
		width: 260px;
	}

We will now use jQuery to “hijack” this link and fire our inline contact form into action:

 // toggle visibility of inline form when link is clicked
$("#a_inline_form").click( function() {

	$("#inline_form").toggle(200);

	$("#inline_form").css( "left", $("#a_inline_form").position().left +
                                                $("#a_inline_form").width() );

	$("#inline_form").css("top", "-40px");

	// get cursor to texarea, ready to receive keystrokes!
	$("#inlinecmt").focus();	

	// return false to prevent default link behaviour
	return false;
});

The above code is fairly self explanatory – I just want to describe how we are positioning the inline form. jQuery allows us to very easily retrieve the left offset position of an element (even when it’s not absolutely or relatively positioned!) using “$(elem).position().left” property.

In this example, I wanted to place the inline form right next to the comment link. To do that, we can simply set the “left” CSS property of the inline form to a value that’s the sum of the left offset of the feedback link and the width of the comment link – this will of course place the inline form right next to the feedback link. In addition, we also set the cursor focus to the inline form so that the textarea is ready to receive input right away.

We have a simple “ok” button underneath the textarea which will be used to submit the form. We will once again “hijack” the form submit event using jQuery and perform the form submission using AJAX. I have omitted the actual form submission and processing here.

$("#inline_form").submit( function() {

	// make your ajax POST call here...

	$("#a_inline_form").after('<span class="msg">Thanks for the comment!' +
                               '</span>');
	$("#inline_form").hide(200);

	setTimeout( '$(".msg").hide()', 2000);

	// return false to prevent default form submission behavior
	return false;
});

Now, once the AJAX call is successful, we need to notify that to the user and thank him for the feedback. I have chosen to do that by inserting a message right after the feedback link and hiding it (using setTimeout() ) after 2 seconds. Don’t forget to hide the inline form too. With that, our inline form is up and ready to go!

This is by no means a replacement for the traditional contact form, but it will be handy in places where one requires casual feedback from users. And as you would have already noticed, we have used JavaScript here unobtrusively – so in case the user has JavaScript disabled, the feedback link merely loads the default contact page.

Writing web applications with CodeIgniter: Part 1

Wednesday, October 21st, 2009

CodeIgniter is a PHP framework that makes writing secure web applications a breeze. Being extremely light weighted, it’s an impressive toolkit which promotes the Model-View-Controller (MVC) approach to software development. CodeIgniter’s incredibly useful libraries, helpers and simplicity give you a sound foundation to quickly build your web apps on. This will be the first part of a series of tutorials focusing on CodeIgniter. Today, let’s get started with the basics of CodeIgniter and familiarize ourselves with the structure and semantics of a CI application.

I am assuming that you are already familiar with the MVC pattern, so let’s briefly see how it applies to a typical CI application.

View – A view is simply the content which a user sees rendered on a any page. It can be either a full web page, or even code snippets like the header or the footer of a web page. The view’s primary aim is to render data on the screen, which will be passed to it by a controller.

Controller – A controller handles the actual application logic. It acts as an intermediate between the View (front end) and the Model (the data). The controller, typically fetches records from a database via a model class, and then passes it to a view for rendering.

Model – A model is concerned with reading and writing data to and from a data souce – in our case, a database. It essentially consists of functions which help you isolate database operations from your core application logic. In CodeIgniter, a model is not necessary, should you wish to manipulate the database from a controller itself.

The URL structure

One great thing about CodeIgniter is that it generates URLs which is search engine friedly and also extremely logical for programmers. Instead of using query strings (like index.php?action=display&id=223) to pass variables, it uses a very semantic segment based URL structure. By default, the CI URLs are parsed this way:

example.com/controller_class_name/function_name/ID1/ID2

As we can see, the first segment of the URL refers to the name of the controller class, the second part referring to the function in the controller that should be invoked, and the subsequent parts representing various parameter values that can be passed to the function. Having understood that, it’s a good time to see the structure of a controller class.

Let’s take a simple example of a blog. Let us say we want a page where we want to show the entries of a blog, we can have a controller "show" which will be defined this way:

class Show extends Controller {

	function index()
	{
		// access a model class to fetch all the blog posts
			...
		// invoke a view and pass to it the blog posts to render
	}
}

There are a couple of things to note here:

  • all controller classes begin with a capital letter in CI – i.e Show
  • we will be saving the above file as "show.php" – the file name is essentially the same as the class name, except that the class name’s first character has to be in capital case.
  • the index() function will be the default function of the class – much like your main() function in a C program!
  • you will access the above controller with the following URL: example.com/show/index or just example.com/show

Remember that the first segment refers to the controller name and the second segment refers to the function name. Since the index function is the default function for the controller, we can leave it out from the URL. We can add another function to the class, called entry – which will display a specific blog entry identified by an identifier:

function entry($entry_id)
{
	// access a model class to fetch the blog post with ID $entry_id
		...
	// invoke a view and pass to it the blog post to render
} 

Now, to display a particular blog entry, we access the URL: example.com/show/entry/123 , where the "123" is (say) the ID of the blog entry to be rendered. Pretty easy, right ?

Now, let’s define a CI model class. Continuing with the same blog example, let’s say that the name of the model class which will handle our blog entries is "Entry_model":

class Entry_model extends Model {

	function Entry_mode()
	{
		parent:Model();
	}

	function fetch_post($entry_id)
	{
		// do your database query and return the record...
	}
}

Now, to invoke the method fetch_post() from the controller, we do:

$this->load->model(Entry_model');
$blog_entry = $this->Entry_model->fetch_post($entry_id); 

Again, it’s very intuitive. We load the model class, and then, invoke a method from the model class which will return the blog entry record. The naming convention for the model class is the same as that for a controller – the class name should start with a capital letter. Thus, the above model class is called "Entry_model" and it will be defined in the file "entry_model.php".

Finally, let’s get to how CodeIgniter handles the View. As I have already stated above, CI is very flexible in how you want to define a view. A view can be a whole page, or page fragments like header, footer, navigation, sidebar etc. It’s always a good practise to logically break down the layout of a web page into a number of components, as it promotes code reusabilty.

As for now, for simplicity, let’s just say that our blog entry will be rendered using a single view. So, we will basically have a .php file that contains the structure (design) of the blog and which will display the blog entry that is passed to it from the controller through the form of variables. Let’s say our view (which display a blog entry) is called "entry_view.php":

<html>
<head>
<title>Showing a blog entry</title>
</head>
<body>

<?php
	echo "<h1>$entry_title</h1>";
	echo $entry_text;
?>

</body>
</html>

When we invoke the view from the controller, we will pass in the variables $entry_title and $entry_text. Here is how we invoke the view we have defined above from a controller:

$data['entry_title'] = "A blog post title";$data['entry_text'] = "Lorem ipsum dolor sit amet...";$this->load->view('entry_view', $data); 

I have shown a very simple example of how data is passed from the controller to a view above. The variables that will be used in the view are defined as elements of an associative array. To load a view, we call it by its filename – we don’t have to use ".php" extension unless we are using some other extension for the view files.

With that, I have covered the basic skeleton of a CI application. Stay tuned for the next article, in which I will walk you through on how to build a simple application using CodeIgniter, and also cover some more advanced concepts along the way!

Writing web applications with CodeIgniter – Part 2

Wednesday, October 21st, 2009

Last week, we covered the basic structure of a CodeIgniter application. Let’s now jump right into developing a simple todo list application using CodeIgniter. We will be keeping the actual functionality of the application itself simple here, as the goal here is to give a good overview on what it takes to build a CI application from scratch.

Okay, the first thing you have to do is to download and extract the latest build of CodeIgniter. Next, download the controllers, models and views that I have used in this sample todo list application. You should refer to these files as you read the tutorial. Here is the demo of the sample application (use “demo” as username and password).

Directory structure

All the files related to our application will be placed in the "system/application" folder:

As you can see, we have to place our controllers, views and models in their correspondng /controllers, /views and /models directories. Initially, we will have a sample controller (Welcome) in the /controllers directory, and its corresponding Welcome view in the /views directory. The model directory will be empty.

The /config directory consists of various files which will help us fine-tune the CI framework to our development environment. We will ignore the other directories in the /application directory for the time being.

Some basic configuration first

We need to modify some of the configuration files in the /config folder to set up the framework:

  • database.php – this is where we will be filling up our database connectivity details. The file has ample comments to help you fill in all the necessary details correctly!
  • config.php – we have to fill in the path to our CI root folder here in the variable: $config['base_url']
  • autoload.php – this file allows us to autoload any libraries or helpers that CodeIgniter provides us so that they are available across the entire system. We will be using the session library and the url helper class, so initialise the $autoload['libraries'] and $autoload['helper'] variables to:

    • $autoload['libraries'] = array(’database’,’session’);
    • $autoload['helper'] = array(’url’);

By default, all CI URLs will have a ".index.php" included in them. E.g. example.com/index.php/blog/edit

To remove this, we can optionally place a .htaccess file in your CI root folder with the following content:

RewriteEngine on
RewriteCond $1 !^(index\.php|images|css|scripts|robots\.txt)
RewriteRule ^(.*)$ index.php/$1 [L] 

With the above rule in place, all requests other than those for index.php, images, css, scripts and robots.txt are treated as a request for your index.php file.

CodeIgniter session class

Before we go further, let’s have a brief review of CodeIgniter’s sessions class, which will be using in this application to keep track of the user’s session. CI’s session class can handle user session data stored using either cookies or in a database. CodeIgniter’s session class does not utilize native PHP sessions. To make use of the session class in our application, we must either initialize it in a controller’s constructor, or we have to auto-load it so that it will run in the background, and will be available for us across the entire system. To load the session class manually in the controller’s constructor, we do that by calling:

$this->load->library('session');

To auto-load the session class, we have to open the file "application/config/autoload.php" and add the item to the "autoload" array as I have mentioned in configuration step above.

Reading and writing data to the session class is a breeze! To write data to a user’s session, we simply do:

$this->session->set_userdata('some_variable', 'some_value'); 

And, to retrieve the data again, we just call:

$item = $this->session->userdata('item');

Apart from that, CI’s session class by default, provides us with the following information:

  • user’s unique Session ID
  • user’s IP Address
  • user’s User Agent data (the first 50 characters of the browser data string)
  • user’s "last activity" time stamp

Our application features:

With that, out of the way, let’s get started. Our to-do-list application will have the following "features":

  • a simple user sign up and login system
  • session management using CI’s session class
  • a single to-do list which allows multiple users to add and delete items using AJAX

Database schema

Given the rather simple nature of our application, it’s not too difficult to identify what database tables we will be needing upfront. We will need two tables:

  • users : stores the user id, username and the hashed password.
  • items : stores the to-do list items and their attributes like item_id, user_id (ID of the user who created it)
CREATE TABLE IF NOT EXISTS `items` (
 `item_id` bigint(20) NOT NULL auto_increment,
 `user_id` bigint(20) NOT NULL,
 `item_text` varchar(255) NOT NULL, `is_done` int(11) NOT NULL,
 PRIMARY KEY  (`item_id`)
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1; 

CREATE TABLE IF NOT EXISTS `users` (
 `user_id` bigint(20) NOT NULL auto_increment,
 `username` varchar(100) NOT NULL,
 `password` varchar(100) NOT NULL,
 PRIMARY KEY  (`user_id`)
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Setting up the above tables in the database which you have mentioned in your database.php configuration file above.

Here is a breakdown of all the controllers, views and model we will be needing for this application. I will explain the purpose of each of them, as we go about tackling them.

Overview of all the CI files 

The login controller

The login controller first checks whether the user is already logged in – in which case, we simply redirect him to the dashboard. This, we do by checking whether the "logged_in" field exists in the user’s session data. We are using CI’s session class for this:

if( $this->session->userdata('logged_in') )	// user already logged in
{
	header("Location: " . base_url() . "index.php" );
	die();
}

The login controller serves two needs:

  • render the login form initially for a user who wants to sign in to the system
  • when the user submits the login form, authenticate the user and either redirect him to the dashboard or show an error message

When the controller is called, we can find out whether we should render the login form, or treat the request as a login form submission by checking for the POST variable ‘login’, which is the name of the "login" submit button in the login form.

if( $this->input->post('login') )
{
	// treat this as a login form submission
}

else {
	// render the login form
}

If it’s NOT a login form submission, we simply load the login_view defined in application/views/login_view.php. This file will render the login form.

On the other hand, if its is a login form submission, we first retrieve the username and password variable from the POST request. We then load the Users_model class, and use its validate() function to authenticate the user. If the user’s username and password match, his user_id field from the database is returned. Else, a -1 is returned. For a valid user, we initialise his session by:

$newdata = array(
 'user_id'  => $user_id,
 'username'  => $username,
 'logged_in' => TRUE
 );

 $this->session->set_userdata($newdata);

We then redirect him to the dashboard. If the username and password provided do not match, we load the login_view by passing a variable ‘$message’ that contains the error to be displayed.

The Dashboard

The welcome controller is the default controller for CodeIgniter. It will already be found in the /application/controllers directory, and this is the controller that will be called when you access our application’s URL directly without using any URL segments, as discussed in the previous article. Let us just make use of this controller for our application’s dashboard. Assuming the user has already logged in successfully, let’s build our application’s dashboard – the page the visitor first sees after logging in. In our case, it will be a page which will display a set of to-do items, and in addition, provide a way to enter a new to-do item or modify the done/not-done status of any existing item using AJAX. Here is the index() function of the welcome controller.

function index()
{

	if( !$this->session->userdata('logged_in') )	// user NOT logged in
	{
		header("Location: " . base_url() . "index.php/login" );
		die();
	} 

 	$this->load->model('items_model','items');
        $data['all_items'] =
$this->items->fetch_all_items($this->session->userdata('user_id'));
 	$this->load->view('dashboard_view',$data);
 }

The welcome controller will check whether the user is logged in (using the session data set earlier in the login controller). If the user is not logged in, or his session has expired, we will redirect him to the login page. The base_url() function belongs to the URL helper that we autoloaded in our configuration, and it returns the base URL of our application (including the "/" at the end of the URL). Otherwise, we will load the Items_model class which will be used to interact with the items table in the database. The fetch_all_items() function of the item_model class will fetch all the todo items of this particular logged in user from the "items" table. The only other thing to note here is that we are using the session class to retrieve the user id of the user that we have stored as session data when the user successfully logs in to the system.

function fetch_all_items($user_id)
{
  // fetch the to-do items of the user identified by $user_id:
  $query = $this->db->query("SELECT * FROM items WHERE user_id = $user_id");
  return $query->result();
} 

The index() function of the Welcome controller then loads the view "dashboard_view", defined in "dashboard_view.php" in the system/application/views directory. When the view is loaded, we are passing to it the todo items we fetched from the database using the Items_model class. The view then renders all the to-do items on the page.

dashboard_view.php links to an external stylesheet (todoapp.css) and a JavaScript file (todoapp.js). The AJAX functionality is defined in the JavaScript file. In our application, we are using AJAX to add a new todo item to the list, and also update the done/not-done status of any of the todo items. The function addNewItem() in the JavaScript file is bound to the click event of the "Add" button.

The addNewItem() function, when fired, makes an AJAX POST request to the "add" controller which will handle the addition of a new todo item. The add controller will return the ID field of the newly added todo item in the database. If the operation is a success (if the ID returned in not -1), we simply append the new todo item (along with a checkbox) to the bottom of the existing items. We also clear the text in the textfield.

The updateItem() function is bound to the click event on each of the checkboxes. When fired, it checks whether the checkbox that the user clicked is selected or not, and it sends this information to the "update" controller.

The add controller

In all the controllers, we will have to first check if the user is logged in, before we carry out any action. For a valid user, we retrieve the text of the new todo item to be added (from the POST variable sent to the script) using:

$this->input->post('item_text',TRUE)

The second parameter is set ‘TRUE’ to indicate that the input must be filtered to negate XSS (cross site scripting) attempts. XSS is a major problem faced by many web applications, and as a golden rule, any input which might potentially get rendered on the front end must be passed through an XSS filter that escapes/strips out the dangerous elements. As an added precaution we also check whether the todo item’s text is not empty, and if all is clear, we load the "Items_model" class once again, and call the add_item() function to add the todo item to the database. The add_item() function uses another handy function that CI provides, to escape the data by adding single quotes around the data:

$item_text = $this->db->escape($item_text);

The update controller

What the update controller does is similar to the add controller and also fairly straight forward. It simply retrieves the POST variables sent to it (the ID of the item which is to be updated, and its updated status). The update controller then loads the Items_model and invokes the update_item() function to peform the update.

The logout controller

The logout controller destroys the session data of the user, and then redirects him to the login page once again.

$this->session->sess_destroy();
header("Location: " . base_url() . "index.php/login" );

User registration

Finally, let’s get to the user registration, which is handled by The Register controller. First off, I should mention here that for the sake of simplicity, I have implemented a very simple registration form, with absolutely no spam control!

The Register controller is similar to the Login controller in that – it again serves both the purposes of rendering the registration form, and as well as handling the form submission. The register_view simply asks the user to pick a username and password. The <form>’s action attribute points to the URL of the register controller.

When the form is submitted, the Register controller first checks to see that both the username and password fields are not empty. It then loads the "Users_model" which handles all database operations concerned with the "Users" table. We will invoke the is_valid_username() of the Users_model to see whether the username that the user has chosen already exists (the function returns a -1 if no such username is found on the system). If it a username is indeed found (in which case the function will return the ID of the user), we will initialise a $message variable with the text "That username already exists." and load the register view again, by passing the $message variable for rendering.

if( $this->users->is_valid_username($this->db->escape($username)) != -1 )
{
	// username already exists
	$data['message'] = "That username already exists.";
}
...
$this->load->view('register_view', $data); 

If the user has chosen a non-existing username, then we go ahead and add the user to the database by calling the Users_model’s add_user() function, by passing the username and his hashed password. We are simply using a plain SHA1 hash here to store the password (which is again considered not secure enough without salting, but enough for our simple application). Once the user is added to the MySQL database, we use the nifty "mysql_insert_id()" PHP function to retrieve the auto increment ID field of the user row just added to the "users" table. After a successful account creation, we initialise the user’s session and redirect him to the dashboard, so the user can start using the application right away.

With that, we come to the end of this second part of CodeIgniter tutorial.