Main Content

Sessions, forms and validation in CodeIgniter - early examples

Archive - Originally posted on "The Horse's Mouth" - 2013-04-13 08:36:31 - Graham Ellis

CodeIgniter is becoming a very popular PHP Framework and increasingly I'm being asked to use/show elements of it on private PHP training courses.

All web based applications need certain elements of code such as form and session handling, data validation, routing of URLs to the appropriate script and separation of business logic from the look and feel of the page, and that's where a web framework come in, in addition to the base language such as PHP (or Ruby or Python or Perl). And CodeIgniter is a really appropriate framework for many of our customers, as it provides plentiful facilities in the major areas in which they're needed without too much bloat.

I wrote a "Hello CodeIgniter World" article [here] just the other day, let's now extend that to take a look at forms and sessions.

Sessions

There's a need in most web applications to remember user's data from one page to the next, and at the same time to ensure that multiple users don't have their data mixed up with one another. There's a need to have that data secured, and cleared away if it's abandoned where someone leaves the site without completion a sale.

PHP has a built in session system, but there's an improved one available in CodeIgniter. Before you can use it, you need to set a security key in application/config/config.php, for example:

  $config['encryption_key'] = 'My training key is easy - yours should be mixedup';

You'll then load the session handler in your controller:

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

and you can read and save data using methods on the session object; here' an example that sets up a 'current' value if one doesn't exist and increments it each time the page is completed. More usually, you'll use session variables to store user names, products selected so far, and the like.

  $pagecount = $this->session->userdata('current');
  if ($pagecount === FALSE) $pagecount = 1;
  $pagecount += 1;
  $this->session->set_userdata('current',$pagecount);


Form Validation

CodeIgniter has a form validation system built in. Again, you need to load the form validator into your controller:

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

and then you can set a whole load of rules:

  $this->form_validation->set_rules('username', 'Username', 'required');
  $this->form_validation->set_rules('password', 'Password', 'required');
  $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');


The rules can be applied in a single "hit", with the controller going on to produce either a refresh of the page for correction, or to save the data / update the model and proceed to the next page:

  if ($this->form_validation->run() === FALSE)
  {
    // Calling for a form to be completed / corrected
    $this->load->view('pages/placetime',$data);
  } else {
    // Update the model here! Move on to next page!
    $this->load->view('pages/success',$data);
  }


Form Display

Within a form, there's usually a requirement echo back a previous value, and the set_value method's provided to let you do that:

  <h5>Username
  <input type="text" name="username" value="<?= set_value('username') ?>" size="50" />


Here's the initial form:



There' also a requirement to flag errors, and there's a validation_errors method to do that:

  <?= validation_errors() ?>

Here's an output sample with some validation issues flagged:



There's far more flexibility than you'll see in this example - you can split the error messages out and put them with each input box if you wish, you can change the text and so on.

Personally, I prefer to wrap up the repetitive elements of form boxes into my own function as that makes for easier maintenance later on, and ensures consistency across each input field. So in an extension of that code above, my input boxes become

  <?= box("Username","username") ?>
  <?= box("yerpassword","password") ?>
  <?= box("AGAIN","passconf") ?>


and there's an extra function provided:

  function box ($prompt,$name) {
  $html = "<h5>$prompt</h5>";
  $html .= '<input type="text" name="' .$name .'" value="' . set_value($name) .'" size="50" />';
  return $html;
  }


And finally the success page:



Links to source code:
Complete controller - [here].
View form - Mark 1 - [here]
View form - with function - [here]
Success page - [here]
Sample routing (via .htaccess) - [here]