আগামী ৩০ অক্টোবর -২০১৭ তারিখ থেকে শুরু হচ্ছে পাঁচ মাস ব্যাপী Professional Web Design and Development with HTML,CSS,Bootstrap,PHP,MySQl, AJAX and JQUERY কোর্সের ৮৬ তম ব্যাচ। আগ্রহীদেরকে অতিসত্বর মাসুদ আলম স্যার এর সাথে যোগাযোগ করতে অনুরোধ করা যাচ্ছে। স্যার এর মোবাইল: 01722817591, Email : [email protected] কোর্সের সিলেবাস এর জন্য এখানে ক্লিক করুন ।

Handling and Validating Form with CodeIgniter

Now we will discuss the handling of form and a way of validating the form input. Form handling means how are we to obtain and process the data sent by the user through the form. To create custom forms, we should use the form helper. Once we managed to get the data from the user, we have to validate the data that has been sent so that the applications we build a safe. Input is not validated to make our applications vulnerable to attacks such as sql injection, XSS and other

Handling Form

to handle the form we need the input library. The library is called automatically by codeigniter. An available function in this library in addition to handle the form also has the function of security / safety. For example, to handle or filter xss we can use the function xss_filter

 $name = $ this-> input-> xss_filter ($ this-> input-> post ('name'));
 

If we want to protect the entire application of the xss filter so we can download the config to change the configuration in system / application / config / config.php from

 $config ['global_xss_filtering'] = FALSE;
 

Be

 $config ['global_xss_filtering'] = TRUE;
 

Besides the two ways above, we can also use the second parameter of the function of the post or get then we will get the same results with both methods, for example

 $this-> input-> post ('name', TRUE);
 $this-> input-get ('name', TRUE);
 

Post function is used to capture the input POST while get used to capture input GET. Besides the input function can also be used for cookies, SERVER variables, and user agent

 $this-> input-> cookie ('name_cokkie', TRUE);
 $this-> input-> ip_address ();
 $this-> input-> server ('PATH_INFO', TRUE);
 

In addition to the input library, CodeIgniter also provides a helper to facilitate the handling of form in view. As for how to load the form helper is

 $ this-> load-> helper ('form');
 

There are many functions provided by these helpers among form_fopen (), form_close (), form_open_multipart (), form_fieldset () and others. For more details you can see on CodeIgniter documentation. In this case, the function is a function of mostly used them form_open (), form_close () and form_input ()
form_open () function to generate the form tag (<form>) in html Example:

 $attributes = array ('class' => 'email', 'id' => 'myform');
 form_open echo ('form / send', $ attributes);
 

Then it will generate

 <form method="POST" accept-charset="utf-8" action="http://localhost/index.php/email/send" class="email" id="myform" />
 

Form_input function to generate the html input tag. This function can be used in two ways. The first way is to include the tag name and its value. Example:

 form_input echo ('username', 'mizan');
 

will produce

 <input type="text" name="username" id="username" value="mizan">
 

The second way is by giving passing arrays into functions. This method is an advanced and very useful if you want to customize the input. For example:

 $ data = array ('name' => 'username',
 'Id' => 'username',
 'Value' => 'mizan',
 'Maxlength' => '100 ',
 'Size' => '50 ',
 'Style' => 'width: 50%',
 );
 form_input echo ($ data);
 

Will produce the output:

 <input type="text" name="username" id="username" value="mizan" maxlength="100" size="50" style="width:50%" />
 

For example handle the form then follow the steps below.

1. Make Controller Count

Keep in mind the first thing that need to be configured on each application is base_url. After configuring the base_url to file application / config.php then we will create a controller that will handle the process of multiplication and division. Configuring the base_url do so using the libraries produce the exact url. Consider the following code:

Application/controllers/arithmetic.php

 <?php

if(!defined('BASEPATH')){

exit('No direct script access allowed');

}

class Arithmetic extends CI_Controller{

function __construct(){

parent::__construct();

$this->load->helper(array('url','form'));

}

function index(){

$this->load->view('count_menus');

}

function multiplication(){

$data['v1']=(int)$this->input->post('v1',true);

$data['v2']=(int)$this->input->post('v2',true);

$data['result']=$data['v1']*$data['v2'];

$this->load->view('multiplication',$data);

}

function division(){

$data['v1']=(int)$this->input->post('v1',true);

$data['v2']=(int)$this->input->post('v2',true);

if($data['v2']>0){

$data['result']=$data['v1']/$data['v2'];

}

else{

$data['result']='Error, v2 can not be 0!';

}

$this->load->view('division',$data);

}

}

?>
 

In line 15, done loading the url helper and form as well. Loading is done the constructor function as both helpers are used on all functions and views that exist. In the index function only contains a call to view. View will contain the menus will hang directing the user to perform multiplication or division.

In multiplication and division functions will do the multiplication or division. At the function, variables derived from the view will be captured using post function (means sent by POST method).

2. Creating View

After creating a controller then we will make a view which is the interface of the application. The following code is a view ‘count_menus’. This view contains the navigation to function multiplication and division.

Application / views /count_menus.php

 <!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8" />

<title>Welcome to CodeIgniter</title>

<style type="text/css">

body{

background-color:#fff;

margin:40px;

font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;

font-size:14px;

color:#4F5155;

}

a{

color:#0003399;

background-color:transparent;

font-weight:normal;

}

h1{

color:#444;

background-color:transparent;

border-bottom:1px solid #D0D0D0;

font-size:16px;

font-weight:bold;

margin:24px 0 2px 0;

padding: 5px 0 6px 0;

}

</style>

</head>

<body>

<h1>CodeIgniter 2.0 and Form</h1>

<p>Please select a menu below</p>

<ul>

<li><?php echo anchor('arithmetic/multiplication','multiplication'); ?></li>

<li><?php echo anchor('arithmetic/division','division'); ?></li>

</ul>

<p><br>Page rendered in {elapsed_time} seconds</p>

</body>

</html>
 

Note the line 67 and the 69, it is an example of the use of helper. Anchor function aims to make a link to a specific page. Here is a view from the view above if called.

Menu with CodeIgniter for Arithmatic OperationFigure 1. Screenshot view count_menus

After a further count menu makes the view to multiplication and division. The view of multiplication is as follows.

Application/views/multiplication.php

 <html lang="en">

<head>

<meta charset="utf-8" />

<title>Welcome to CodeIgniter</title>

<style type="text/css">

body{

background-color:#fff;

margin:40px;

font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;

font-size:14px;

color:#4F5155;

}

a{

color:#003399;

background-color:transparent;

font-weight:normal;

}

h1{

color:#444;

background-color:transparent;

border-bottom:1px solid #D0D0D0;

font-size:16px;

font-weight:bold;

margin: 24px 0 2px 0;

padding: 5px 0 6px 0;

}

</style>

</head>

<body>

<h1>Arithmetic!</h1>

<p> Please enter the following data!</p>

<?php echo form_open('arithmetic/multiplication'); ?>

<?php echo form_input('v1',$v1); ?>X

<?php echo form_input('v2',$v2);?><br>

<?php echo form_submit('submit','Arithmetic!!'); ?>

<?php echo form_close(); ?><br>

Result : <?php echo $result; ?>

<p><br>Page rendered in {elapsed_time} seconds</p>

</body>

</html>
 

In this view helper widely used form (lines 65-69). Existing input tag is generated by the view form_input and function by function form_submit submit button. As for the display detailed view is

A form with CodeIgniter

Figure 2. Screenshot view multiplication

The latter is making a view to distribution. In principle, make it the same as the form layout view multiple but different

Application/views/division.php

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>Welcome to CodeIgniter</title>

<style type="text/css">

body{

background-color:#fff;

margin:40px;

font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;

font-size:14px;

color:#4F5155;

}

a{

color:#003399;

background-color:transparent;

font-weight:normal;

}

h1{

color:#444;

background-color:transparent;

border-bottom:1px solid #D0D0D0;

font-size:16px;

font-weight:bold;

margin: 24px 0 2px 0;

padding: 5px 0 6px 0;

}

</style>

</head>

<body>

<h1>Division!</h1>

<?php echo form_open('arithmetic/division'); ?>

<?php echo form_input('v1',$v1); ?>/

<?php echo form_input('v2',$v2);?><br />

<?php echo form_submit('submit','Arithmetic!!'); ?>

<?php echo form_close(); ?><br />

Result: <?php echo $result; ?>

<p><br /> Page rendered in {elapsed_time} seconds</p>

</body>

</html>
 

Here is a view of the form distribution

A Form with CodeIgniter

Figure 3. Screenshot view Division

Using Form Validation

Actually, come to the second stage of the above we have been able to make an application multiplication and division simple, but a good application should have a control over user input.

Validation is essential in the application form. An application will have a lot of input from the users and all user input to be safe. CodeIgniter Form Validation library has a Library that will help us to create a validation quick, easy and safe.

In the example of form validation is similar to the 2 steps above, but has a slight increase in especially in multiplication and division functions. Consider the following arithmetic controller (The following controller is derived from the previous example with the addition).

Application/controllers/secureArithmatic.php

 <?php

if(!defined('BASEPATH')){

exit('No direct script access allowed');

}

class secureArithmatic extends CI_Controller{

function __construct(){

parent::__construct();

$this->load->helper(array('url','form'));

}

function index(){

$this->load->view('count_menus');

}

function multiplication(){

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

$this->form_validation->set_rules('v2','variables 1','required|integer');

$this->form_validation->set_rules('v2','variables 2','required|integer');

if($this->form_validation->run()){

$data['v1']=(int)$this->input->post('v1',true);

$data['v2']=(int)$this->input->post('v2',true);

$data['result']=$data['v1']*$data['v2'];

}

else{

$data['v1']=0;

$data['v2']=0;

$data['result']=0;

}

$this->load->view('secure_multiplication',$data);

}

function division(){

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

$this->form_validation->set_rules('v2','variables 2','required|is_natural_no_zero');

if($this->form_validation->run()){

$data['v1']=(int)$this->input->post('v1',true);

$data['v2']=(int)$this->input->post('v2',true);

$data['result']=$data['v1']/$data['v2'];

}

else{

$data['v1']=0;

$data['v2']=0;

$data['result']=0;

}

$this->load->view('secure_division',$data);

}

}

?>
 

Notice lines 29-39 on the function of multiplication, there we load a library named form_validation. The library has a function to validate the user input based on the rules that we have specify. Note line 29,31

$ this> form_validation-> set_rules (‘v2’, ‘variables 1’, ‘required | integer’);

The line above is one example of the rules for determining input on the form. The first parameter (containing v1) is the name of the input to be validated (must be equal to the name attribute on the input tag example: <input name=”v1″>). The second parameter is the name of the input. These names can be different
or equal to the name in the first parameter. The third parameter is the rule of the input. The rules must be adhered to in order for a form to be processed. Rules are separated by |
in the above example means v1 input the required fields (required) and contains integer data (integer). The rules provided in CodeIgniter are:

required: Fill input cannot be empty

matches: Content input must equal the given input instance matche [‘password’]

min_length: Input length must have a minimum number of characters, for example max_length [12] means Input length cannot be longer than 12 characters.

exact_length: Input length must be equal to the number of characters you want; exact_length example [8] denotes input length must be equal to 8 characters.

alpha: Input should contain all letters of the alphabet from a-z

alpha_numeric: Input must contain alphabetic and numeric characters.

alpha_dash: Input should contain all letters of the alphabet from az, underscores or dashes.

numeric: input should only contain numbers / letters numeric.

integer: Input integer can only contain integer numbers only.

is_natural: input may only contain only natural numbers: 0, 1, 2, 3, and so on.

is_natural_no_zeros: Input only contain natural numbers except zero: 1,2,3, and so on.

valid_email: Input must contain the correct email format.

valid_emails: Input must contain the correct email format limit by commas if more than one emails address.

valid_id: Input must contain the correct IP format.

Valid_base64: Input must contain the correct format base64 characters.

At line 33 and 63, we did check on some rules that have been set ($ this-> form_validation-> run ()).

That function will return the value TRUE if all rules are met and produce a false value otherwise. In addition to the above functions you can create custom validation if the rules above do not exist that meets your needs

Application/views/ secure_multiplication.php

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>Multiplication with validation!</title>

<style type="text/css">

body{

background-color:#fff;

margin:40px;

font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;

font-size:14px;

color:#4F5155;

}

h1{

color:#444;

background-color:transparent;

border-bottom:1px solid #D0D0D0;

font-size:16px;

font-weight:bold;

margin:24px 0 2px 0;

padding:5px 0 6px 0;

}

</style>

</head>

<body>

<h1>Multiplication!</h1>

<?php echo validation_errors(); ?>

<p>Please enter the following data!</p>

<?php echo form_open('secureArithmatic/multiplication'); ?>

<?php echo form_input('v1',$v1);?>X

<?php echo form_input('v2',$v2); ?><br />

<?php echo form_submit('submit','Arithmetic!!'); ?>

<?php echo form_close(); ?><br />

Result: <?php echo $result; ?>

<p><br>Page rendered in {elapsed_time} seconds</p>

</body>

</html>
 

In the view, we simply add a function that allows you to display the error.

Note the line 38. validations_error function is a function to display an error from the validation performed.

A Form With CodeIgniterFigure 4. Form multiplication with error display

Similarly to view the distribution, we simply add a function to display the error validations_error on the form distribution. The code that can be used is

Application/views/ secure_division.php

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>Welcome to CodeIgniter</title>

<style type="text/css">

body{

background-color:#fff;

margin:40px;

font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;

font-size:14px;

color:#4F5155;

}

a{

color:#003399;

background-color:transparent;

font-weight:normal;

}

h1{

color:#444;

background-color:transparent;

border-bottom:1px solid #D0D0D0;

font-size:16px;

font-weight:bold;

margin: 24px 0 2px 0;

padding: 5px 0 6px 0;

}

</style>

</head>

<body>

<h1>Division!</h1>

<?php echo validation_errors(); ?>

<?php echo form_open('secureArithmatic/division'); ?>

<?php echo form_input('v1',$v1); ?>/

<?php echo form_input('v2',$v2);?><br />

<?php echo form_submit('submit','Arithmetic!!'); ?>

<?php echo form_close(); ?><br />

Result: <?php echo $result; ?>

<p><br /> Page rendered in {elapsed_time} seconds</p>

</body>

</html>
 

view of the above will give as figure 5 below.

A Form with codeigniterFigure 5. Form multiplication with error display

Happy CodeIgniter 🙂

Hi, My name is Masud Alam, love to work with Open Source Technologies, living in Dhaka, Bangladesh. I graduated in 2009 with a bachelor's degree in Engineering from State University Of Bangladesh, I'm also a Certified Engineer on ZEND PHP 5.3, I served my first five years a number of leadership positions at Winux Soft Ltd, SSL Wireless Ltd, CIDA and MAX Group where I worked on ERP software and web development., but now i'm a co-founder and Chief Executive Officer and Managing Director of TechBeeo Software Consultancy Services Ltd. I'm also a Course Instructor of ZCPE PHP 7 Certification and professional web development course at w3programmers Training Institute - a leading Training Institute in the country.
6 comments on “Handling and Validating Form with CodeIgniter
    • Looks like paranoid mode.
      validate integer, filter xss on interger, cast to integer.

      29 $this->form_validation->set_rules(‘v2′,’variables 1′,’required|integer’);
      30
      31 $this->form_validation->set_rules(‘v2′,’variables 2′,’required|integer’);
      32
      33 if($this->form_validation->run()){
      34
      35 $data[‘v1’]=(int)$this->input->post(‘v1’,true);

  1. Thank you very much for this codeigniter tutorial, I never thought this much easy.. It makes my life happy . happy Codeignitering 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *