Codeigniter - SPLessons

CodeIgniter Form Validation

Home > Lesson > Chapter 21
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

CodeIgniter Form Validation

CodeIgniter Form Validation

shape Description

Forms have become most important section in any web application as they interact with the users and store/retrieve the data. There are two stages in forming a CodeIgniter Form.

CodeIgniter Form Validation rule

shape Description

Rules can be defined for a form in two ways either pre-define it in a config.php file or define dynamically in the controller function. First way of defining is better if configuration is defined on multiple controller functions. For Example, [php] $config['contact_rules'] = array( 'name' => array( 'field' => 'name', 'label' => 'Name', 'rules' => 'trim|required|xss_clean' ), 'email' => array( 'field' => 'email', 'label' => 'Email', 'rules' => 'trim|required|valid_email' ), 'subject' => array( 'field' => 'subject', 'label' => 'Subject', 'rules' => 'trim|required|xss_clean' ), 'message' => array( 'field' => 'message', 'label' => 'Message', 'rules' => 'trim|required|xss_clean' ) ); [/php] In the above code, the Codeigniter forms configuration has two-dimensional key/value pair based array in which the first defines fields and second dimension defines three different property of each item. Like,
  • field: name attribute of that field.
  • label: label text of that field.
  • rules: denotes the conditions that has to be satisfied. -> 'required' denotes that form validation class should not be empty. -> 'valid_email' rule denotes that the inputted email must have correct format. -> 'trim' rule performs removal operation on the input that was submitted. -> ‘xss_clean’ rule protects from security threats.
Likewise, the rules can be given in the controller function dynamically as shown below: [php] $this->form_validation->set_rules('name', 'Name', 'trim|required|xss_clean'); $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email'); $this->form_validation->set_rules('subject', 'Subject', 'trim|required|xss_clean'); $this->form_validation->set_rules('message', 'message', 'trim|required|xss_clean'); [/php]

Building the form

shape Step-1

Create the login form, Signup form and Admin Page to interact with the users. For this purpose, CodeIgniter Form Helper is used instead of writing HTML code.

Form Helper

Form Helper has the functions which helps in creating various form segments. For example, Submit button, InputBox , Dropdown boxes. To create the segments, form helper library must be loaded initially which is done in two methods.
  • Configure in autoload.php present in application/config as shown below.
    $autoload['helper'] = array(‘form’);
  • In controller function, use $this->load->helper(‘form’) ;
Below are some of the form helper functions: [php] form_open( ); //create an opening form tag form_label( ); //create a label form_input( ); //create input field such as text , email etc. form_password( ); //create a password input field form_hidden( ); //create hidden field form_radio( ); //create radio button form_dropdown( ); //create select field form_checkbox( ); //create checkbox form_textarea( ); //create textarea form_fieldset( ); //create fieldset form_upload( ); //to upload files form_submit( ); //create submit button form_reset( ); //create reset button form_close( ); //create form closing tag set_value( ) ; //set default value for input tag set_select( ); //set default value for select field set_checkbox(); //set default value for checkbox set_radio(); //set default value for radio button [/php]
login_form.php [php] <html> <?php if (isset($this->session->userdata['logged_in'])) { header("location: http://localhost/login/index.php/user_authentication/user_login_process"); } ?> <head> <title>Login Form</title> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/style.css"> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'> </head> <body> <?php if (isset($logout_message)) { echo "<div class='message'>"; echo $logout_message; echo "</div>"; } ?> <?php if (isset($message_display)) { echo "<div class='message'>"; echo $message_display; echo "</div>"; } ?> <div id="main"> <div id="login"> <h2>Login Form</h2> <hr/> <?php echo form_open('user_authentication/user_login_process'); ?> <?php echo "<div class='error_msg'>"; if (isset($error_message)) { echo $error_message; } echo validation_errors(); echo "</div>"; ?> <label>UserName :</label> <input type="text" name="username" id="name" placeholder="username"/><br /><br /> <label>Password :</label> <input type="password" name="password" id="password" placeholder="**********"/><br/><br /> <input type="submit" value=" Login " name="submit"/><br /> <a href="<?php echo base_url() ?>index.php/user_authentication/user_registration_show">To SignUp Click Here</a> <?php echo form_close(); ?> </div> </div> </body> </html> [/php] registration_form.php [php] <html> <?php if (isset($this->session->userdata['logged_in'])) { header("location: http://localhost/login/index.php/user_authentication/user_login_process"); } ?> <head> <title>Registration Form</title> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/style.css"> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'> </head> <body> <div id="main"> <div id="login"> <h2>Registration Form</h2> <hr/> <?php echo "<div class='error_msg'>"; echo validation_errors(); echo "</div>"; echo form_open('user_authentication/new_user_registration'); echo form_label('Create Username : '); echo"<br/>"; echo form_input('username'); echo "<div class='error_msg'>"; if (isset($message_display)) { echo $message_display; } echo "</div>"; echo"<br/>"; echo form_label('Email : '); echo"<br/>"; $data = array( 'type' => 'email', 'name' => 'email_value' ); echo form_input($data); echo"<br/>"; echo"<br/>"; echo form_label('Password : '); echo"<br/>"; echo form_password('password'); echo"<br/>"; echo"<br/>"; echo form_submit('submit', 'Sign Up'); echo form_close(); ?> <a href="<?php echo base_url() ?> ">For Login Click Here</a> </div> </div> </body> </html> [/php] admin_page.php : If the user login without any errors, they are directed to admin page. [php] <html> <?php if (isset($this->session->userdata['logged_in'])) { $username = ($this->session->userdata['logged_in']['username']); $email = ($this->session->userdata['logged_in']['email']); } else { header("location: login"); } ?> <head> <title>Admin Page</title> <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/style.css"> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'> </head> <body> <div id="profile"> <?php echo "Hello <b id='welcome'><i>" . $username . "</i> !</b>"; echo "<br/>"; echo "<br/>"; echo "Welcome to Admin Page"; echo "<br/>"; echo "<br/>"; echo "Your Username is " . $username; echo "<br/>"; echo "Your Email is " . $email; echo "<br/>"; ?> <b id="logout"><a href="logout">Logout</a></b> </div> <br/> </body> </html> [/php]

shape Step-2

Make sure to set the base URL in config.php file as shown below. [php]$config['base_url'] = 'http://localhost/login/';[/php]

shape Step-3

Then, create the database login with the table <user_login. [sql] create database login; CREATE TABLE IF NOT EXISTS `user_login` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_name` varchar(255) NOT NULL, `user_email` varchar(255) NOT NULL, `user_password` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) [/sql]

shape Step-4

In this step, CodeIgniter Form Validation is set to all input fields using controller named user_authentication.php in the folder application/controllers and enter the below code. When the form is submitted, user existence is also checked in the database. [php] <?php session_start(); //we need to start session in order to access it through CI Class User_Authentication extends CI_Controller { public function __construct() { parent::__construct(); // Load form helper library $this->load->helper('form'); // Load form validation library $this->load->library('form_validation'); // Load session library $this->load->library('session'); // Load database $this->load->model('login_database'); } // Show login page public function index() { $this->load->view('login_form'); } // Show registration page public function user_registration_show() { $this->load->view('registration_form'); } // Validate and store registration data in database public function new_user_registration() { // Check validation for user input in SignUp form $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean'); $this->form_validation->set_rules('email_value', 'Email', 'trim|required|xss_clean'); $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean'); if ($this->form_validation->run() == FALSE) { $this->load->view('registration_form'); } else { $data = array ( 'user_name' => $this->input->post('username'), 'user_email' => $this->input->post('email_value'), 'user_password' => $this->input->post('password') ); $result = $this->login_database->registration_insert($data); if ($result == TRUE) { $data['message_display'] = 'Registration Successfully !'; $this->load->view('login_form', $data); } else { $data['message_display'] = 'Username already exist!'; $this->load->view('registration_form', $data); } } } // Check for user login process public function user_login_process() { $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean'); $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean'); if ($this->form_validation->run() == FALSE) { if(isset($this->session->userdata['logged_in'])) { $this->load->view('admin_page'); } else { $this->load->view('login_form'); } } else { $data = array( 'username' => $this->input->post('username'), 'password' => $this->input->post('password') ); $result = $this->login_database->login($data); if ($result == TRUE) { $username = $this->input->post('username'); $result = $this->login_database->read_user_information($username); if ($result != false) { $session_data = array( 'username' => $result[0]->user_name, 'email' => $result[0]->user_email, ); // Add user data in session $this->session->set_userdata('logged_in', $session_data); $this->load->view('admin_page'); } } else { $data = array( 'error_message' => 'Invalid Username or Password' ); $this->load->view('login_form', $data); } } } // Logout from admin page public function logout() { // Removing session data $sess_array = array( 'username' => '' ); $this->session->unset_userdata('logged_in', $sess_array); $data['message_display'] = 'Successfully Logout'; $this->load->view('login_form', $data); } } ?> [/php]

shape Step-5

Further, username and password is checked in the database and if present, respective data is shown. login_database.php [php] <?php Class Login_Database extends CI_Model { // Insert registration data in database public function registration_insert($data) { // Query to check whether username already exist or not $condition = "user_name =" . "'" . $data['user_name'] . "'"; $this->db->select('*'); $this->db->from('user_login'); $this->db->where($condition); $this->db->limit(1); $query = $this->db->get(); if ($query->num_rows() == 0) { // Query to insert data in database $this->db->insert('user_login', $data); if ($this->db->affected_rows() > 0) { return true; } } else { return false; } } // Read data using username and password public function login($data) { $condition = "user_name =" . "'" . $data['username'] . "' AND " . "user_password =" . "'" . $data['password'] . "'"; $this->db->select('*'); $this->db->from('user_login'); $this->db->where($condition); $this->db->limit(1); $query = $this->db->get(); if ($query->num_rows() == 1) { return true; } else { return false; } } // Read data from database to show data in admin page public function read_user_information($username) { $condition = "user_name =" . "'" . $username . "'"; $this->db->select('*'); $this->db->from('user_login'); $this->db->where($condition); $this->db->limit(1); $query = $this->db->get(); if ($query->num_rows() == 1) { return $query->result(); } else { return false; } } } ?> [/php]

Summary

shape Key Points

CodeIgniter Form Validation chapter draws out following important points.
  • CodeIgniter forms are formed with form helper that creates the various section of form.
  • CodeIgniter Form Validation are done validation rules of CodeIgniter.