Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login

You must be logged to download. Click here to login


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Working with Session Library and Helpers in CodeIgniter

In this article we will talk about session library, we will learn how to load it and use it with PHP code.

In our previous article, we discussed CodeIgniter, and its libraries. In this article we will continue from discussing session library, as it’s most important and frequently used library. We will learn how to load it and use it. Further we will continue to discuss CodeIgniter helpers. Like libraries, they alsomake the developer life easy by providing various functionalites, which you can use directly, instead of writing code from scratch and hence save your precious time. We will try to discuss Form helper and URL helper completely as they are mostly used. After learning this article, you will be able to use helpers and libraries easly and your mind level will be set to use CodeIgniter documentation on your own.

The session library.

You may be familiar with PHP sessions. The CodeIgniter sessions are somewhat similar to PHP sessions but are separate from them. For example, CodeIgniter stores session data by default in a Cookie, or they may be stored in a database table. This is different from the PHP sessions, which are saved on server side. So if you are a security conscious, you should use PHP sessions as they are athentic, even if you store your CodeIgniter session in a database. The same data is also stored on a client side cookie, which is accessible to users. So avoid CodeIgniter session if you need secure login and authentication. CodeIgniter sessions track a session ID, the user’s IP address and user agent, and time stamps for the last activity and the last visit.

Initializing a session Sessions will typically run globally with each page load. So the session class should either be initialized in your controller constructors, or it can be auto-loaded by the system. For the most part, the session class will run unattended in the background. So simply initializing the class will cause it to read,create,and update sessions when necessary.To initialize the session class manually in your controller consturctor, use the $this->load->library( ) method.

Listing 1: Loading session library manually.

The code in Listing 1, is used for loading session library. Listing 2: Sessions library object accessibility.

When you load a session library, it’s object will be availaible through the code shown in Listing 2. Another way to initialize a session library is to autoload it. Once you autoload a session library, you don’t need to do further steps to work with CodeIgniter session data.

To Retrieve data from CodeIgniter session To retrieve a CodeIgniter session’s session_id, do it this way:

Listing 3: Retrieving session_id.

  $sess_id = $this->session->userdata(‘session_id’);

In Listing 3, we used session object for accessing userdata( ) function. Inside that function we passed session_id, as a parameter. Finally the session_id is assigned to $sess_id variable. The userdata( ) function will return FALSE if the item you are trying to access doesn’t exist.

CodeIgnitor Helpers

Helpers are different from libraries and are not object oriented but procedural in nature. Helpers contains specific functions, each focusing on a specific task, with zero dependence on other functions. So viewing the functionalities of helpers, it is obvious that they will help you with specific tasks.Helpers can automatically be loaded or they can be loaded locally, manually. Let’s have a look on CodeIgniter helpers.

Array: The array helper contains functions which will help you to work with arrays. For example the random element function random_element( ). This function takes array as an input and returns a random element from it. For checking other functions refer to CodeIgniter documentation.

Captcha Helper: The captcha helper provides functions for creating CAPTCHA images.

Cookie Helper: The cookie helper contains fucntions that help you set, read, and delete cookie data.

Date Helper: The date helper contains functions that help you work with dates. For example the now(), function returns the current time as a UNIX time stamp.

Directory Helper: The directory helper contains a single function that helps you work with directories. For example, the directory_mape( ) function, reads a specified directory path and builds an array of it that contains all of its files and subdirectories.

Download Helper: The download helper contains a single funtion that helps you download data easily. The force_download( ) function, creates server headers that force data to be downloaded instead of viewing in the browser.

Email Helper: This helper is DEPRECATED and is currently only kept for backwards compatibility. This helper provides functions for working with Email. For example the valid_email( ) function, accepts E-mail address as a parameter and returns true if valide email is supplied otherwise FALSE.

File Helper: This helper contains functions that assist in working with files.Various functions are present for writing, reading, and deleting of files.

Form Helper: The most usable helper of CodeIgniter is the the Form helper. It contains functions that help you build forms.

HTML Helper: The HTML helper contains functions that help you create HTML blocks quickly and easily. For example, the ul( ) function can turn an array of items into a bulleted list.

Inflector Helper: The Inflector helper contains functions that help you to turn words into plural or singular form, to apply camel case, or to turn words separated by spaces into an underscored phrase. For example, the singular( )function can turn the string “cats” into “cat”.

Language Helper: The language helper contains functions that help you in working with language files.

Number Helper: These helpers contains functions that help you work with numeric data.

Path Helper: This helper contains functions that permit you to work with file paths on the server.

Security Helper: The Security helper contains security-related functions like xss_clean( ), which filters out any code that may be used in a cross site scripting hack.

Smiley: The Smiley helper contains functions that help you manage emotions. The functions in this helper might seem superfluous, but become invaluable if you are coding a bulletin board or chat application.

String Helper: The String helper contains functions that help you work with strings, like the random_string( ) function, which as its name implies, creates random strings based on type and length arguments.

Text Helper: The Text helper contains functions that help you work with text. For example, the word_limiter( ) function can limit a string to a certain number of words, which is useful if you’re trying to limit user input on a form.

Typography Helper: The Typography helper contains a single function that helps you format text in appropriate ways. For example, the auto_typography( ) function wraps paragraphs with and converts line breaks to and converts quotes, dashes, and ellipses properly.

URL Helper: The URL helper contains functions that help you work with URLs. This is another helper that sees heavy use. You will use the base_url( ) and anchor( ) functions many times in any given project, but other functions, such as safe_mailto( ) and anchor_popup( ) are extremely useful as well.

XML Helper: The XML helper contains a single function that helps you work with XML.The xml_convert( ) function converts a given string into XML - ready text, converting ampersands and angle brackets (among other things) into entities. Like libraries we will cover only those helpers in details which will be frequently used in our future projects. So here we will discuss Form and URL helper in detail.

The Form Helper

One of the most useful helpers in the CodeIgniter toolbox is the Form helper. It is difficult to create a form from scratch as it willbe time consuming. So the functions present in Form helper help you keep things straight when working with forms. Making forms in CodeIgniter is quite different from the method we used in HTML. So, we must have a proper knowldege about making forms in CodeIgniter. To use functions of form helper, first load it. The form helper can be loaded by two methods:

Manually: Insert the following code in Listing 1, within the controller.

Automatically: By autoloading in autoload.php file, which is availabe by opening appliaction/config/autoload.php.

Listing 4: Code for loading form helper within controller.


In Listing 4, we simply load the form helper through $this variable. After loading form helper, we will be able to use its various functions. Now let’s have a look at function which are availible within this helper.



form_open( );

For creating an opening tag.

form_label( );

For creating a label.

form_input( );

For creation of input field like email,text etc.

form_passwrod( );

For creating a password field.

form_radio( );

For creating a radio button

form_hidden( );

For creating a hidden field within form.

form_dropdown( );

For creating a select field.

form_checkbox( );

For creating a checkbox.

form_textarea( );

For creating a textarea.

form_upload( );

For uploading of files.

form_fieldset( );

For creating fieldset.

form_submit( );

For creating submit button.


For creating reset button.

form_close( );

For closing form tag.

set_value( );

For setting default value for input tag.

set_select( );

For setting default value for select field.

set_checkbox( );

For setting default value for checkbox.

Let’s start from very basic and prepare a form using form helper. Remember that preceeding further we have loaded the form helper automatically. First write the controller code, as shown in Listing 5.

Listing 5: Controller code for displaying a form in view.

  class Form_controller extends CI_Controller {
  public function __construct() {
  public function index() {
  // load form.php present in views folder

In Listing 5, we have created a controller namely form_controller.php. Within the controller we created a class which extends the core class of controller. Note that the class name should be same as that of the controller. Within the class a constructor is created, inside which a parent constructor is also called. Another function called index( ), is also formed for loading of view. Remember that we have’t created a view yet but passed its name as a parameter to view function.

Listing 6: Code for displaying form in view (form.php).

  echo "<b>Html form using form helper in CodeIgniter</b></br>";
  //create form open tag
  echo "<br>".form_open('form');
  //create label
  echo form_label('Student Name:');
  //create name input field
  $data_name = array(
  'name' => 'std_name',
  'id' => 'st_id',
  'class' => 'input_box',
  'placeholder' => 'Please Enter Name');
  echo form_input($data_name)."</br>";
  echo "<br>". form_label('Student Email-ID');
  //create email input field
  $data_email = array(
  'type' => 'email',
  'name' => 'std_email',
  'id' => 'std_email_id',
  'class' => 'input_box',
  'placeholder' => 'Please Enter Email');
  echo form_input($data_email)."<br>";
  echo "<br>".form_label('Password');
  //create password field
  $data_password = array(
  'name' => 'password',
  'id' => 'password_id',
  'class' => 'input_box',
  'placeholder' => 'Please Enter Password');
  echo form_password($data_password)."<br>";
  echo "<br>".form_label('Gender');
  //create dropdown box
  $data_gender = array(
  'Male' => 'Male',
  'Female' => 'Female');
  echo  form_dropdown('select', $data_gender, 'Male');
  echo "<br>".form_label('Marital status:');
  //create radio button
  $data_radio1 = array(
  'name' => 'std_marital_status',
  'value' => 'Unmarried',
  'checked' => TRUE);
  echo form_radio($data_radio1);
  echo form_label('Unmarried');
  $data_radio2 = array(
  'name' => 'std_marital_status',
  'value' => 'Married');
  echo form_radio($data_radio2);
  echo form_label('Married');
  echo form_label('Qualification');
  //create checkbox
  $data_checkbox1 = array(
  'name' => 'qualification[]',
  'value' => 'Graduation');
  echo form_checkbox($data_checkbox1);
  echo form_label('Graduation');
  $data_checkbox2 = array(
  'name' => 'qualification[]',
  'value' => 'Post Graduation');
  echo form_checkbox($data_checkbox2);
  echo form_label('Post-Graduation');
  echo form_label('Address');
  //create textarea
  $data_textarea = array(
  'name' => 'address',
  'rows' => 5,
  'cols' => 32);
  echo form_textarea($data_textarea);
  echo form_label('Upload Image');
  //create upload section
  $data_upload = array(
  'type' => 'file',
  'name' => 'file_upload',
  'value' => 'upload resume');
  echo form_upload($data_upload);
  create reset button -->
  <?php echo form_reset('reset', 'Reset'); ?>
  <!-- create submit button -->
  <?php echo form_submit('submit', 'Submit'); ?>
  <!-- close form tag -->
  <?php echo form_close(); ?>

Listing 6, is all about creating a form using form helper functions of CodeIgniter. The form_open() function creates an opening form tag which contains a base URL built in the config preferences. it will always add the attribute accept-charset based on the charset value in the config file.

form_label( ), function will generate a simple label.Its equivalent HTML code is shown in Listing 7.

Listing 7: Equivalent HTML code for form_label( ).

  echo form_label('student Email-ID');
  //alternate HTML code for above function to create a label.
  <label>student Email-ID</label>

form_input( ), function will allow you to generate a standard text input field. Here we used $data_name array which contains indexes and values to create different input fields. This array is then passed to form_input( ) function to create text input field. Alternate code for form_input( ) function is shown in Listing 8.

Listing 8: Alternate HTML code for form_input( ).

  $data_name = array(
  'name' => 'std_name',
  'id' => 'std_name_id',
  'placeholder' => 'Please Enter Name');
  echo form_input($data_name);
  //Alternate HTMl code is
  <input type="text" name="std_name" value="" id="std_name_id" placeholder="Please Enter Name"  />

Code for email and password field generation is the same as the one used for creating an input type field.

For gender selection we used form_dropdown( ) function to create standard dropdown field. This function accepts three parameters: first is name of dropdown field, second parameter contains associative arrays of options needed in dropdown and third parameter contains the value which will be selected by default.

Equivalent HTML code for form_dropdown( ) function is given in Listng 9.

Listing 9: Alternate HTML code for form_dropdown ( ).

  $data_gender = array(
  'Male' => 'Male',
  'Female' => 'Female'
  echo form_dropdown('select', $data_gender, 'Male');
  //Alternate HTML code is 
  <select name="select">
  <option value="Male" selected="selected">Male</option>
  <option value="Female">Female</option>

For creating a radio button, form_radio( ) is used. As we know, a radio button is used for single selection so its name attribute must be the same. To understand it, let's see its alternate HTML code in Listing 10.

Listing 10: Alternate HTML code for form_radio ( ).

  $data_radio1 = array(
  'name' => 'std_marital_status',
  'value' => 'Unmarried',
  'checked' => TRUE);
  $data_radio2 = array(
  'name' => 'std_marital_status',
  'value' => 'Married');
  echo form_radio($data_radio1);
  echo form_radio($data_radio2);
  //Alternate HTML code for form_radio();
  <input type="radio" name="std_marital_status" value="Unmarried" checked="checked"/>
  <input type="radio" name="std_marital_status" value="Married"/>

For multiple selection, we used a checkbox field. To create it in CodeIgniter we used form_checkbox( ) function. Let’s see its alternative HTML code in Listing 11 to understand it better.

Listing 11: Alternative HTML code for form_checkbox( ).

  $data_checkbox1 = array(
  'name' => 'qualification[]',
  'value' => 'Graduation');
  $data_checkbox2 = array(
  'name' => 'qualification[]',
  'value' => 'Post Graduation');
  echo form_checkbox($data_checkbox1);
  echo form_checkbox($data_checkbox2);
  // Alternative HTML code for form_checkbox( );
  <input type="checkbox" name="qualification[ ]" value="Graduation" />
  <input type="checkbox" name="qualification[ ]" value="Post Graduation" />

For creating a textfield area in CodeIgniter , we used form_textarea( ) function. We also passed an array to this function. Array is used for defining width and height of textarea.

Equivalent HTML code for form_textarea( ) for Listing 12.

Listing 12: Equivalent HTML Code for form_textarea( ).

  $data_textarea = array(
  'name' => 'textarea',
  'rows' => 10,
  'cols' => 50
  echo form_textarea($data_textarea);
  //Aternate HTML code for form_textarea( );
  <textarea name="textarea" cols="50" rows="10" ></textarea>

For file uploading , form_upload( ) function is used to create an upload field. For this purpose, we only passed an associative array with index ‘type’ and value ‘file’. Alternate HTML code of form_upload( ) function in given in Listing 13.

Listing 13: Alternative HTML code for form_upload( ).

  $data_upload = array(
  'type' => 'file',
  'name' => 'file_upload');
  echo form_upload($data_upload);
  // Aternate HTML code for form_upload( ).
  <input type="file" name="file_upload" value=""/>

Toward the end of the code, we used two buttons. One is Submit button, while the second is Reset button. For this purpose we used form_submit( ) , form_reset( ) and form_close( ) functions to create the required buttons. Alternative HTML code for understanding purpose is given in Listing 14.

Listing 14: Alternative HTML code for form_submit( ) and form_reset( ).

  <?php echo form_submit('submit', 'Submit'); ?>
  //Alternative HTML code for form_submit( ). 
  <input type="submit" name="submit" value="Submit"  />
  <?php echo form_reset('reset', 'Reset'); ?>
  //Alternative HTML code for form_reset( )
  <input type="reset" name="reset" value="Reset" />
  <?php echo form_close( ); ?>
  //Alternate HTML code for form_close();

Figure 1. Shows the form which is formed after executing the code.

URL Helper

Another extremely useful helper in the URL helper. It contains functions which will help you call, create and maintain a URL. The URL helper can also be loaded manually or automatically. Same as we have done for form helper. The URL helper contains various functions that help in working with URLs. base_url( ): This function will return your base URL. For example

Listing 15: Using base_url( ) in view to return base URL.

  echo base_url( );

The code in Listing 15, will returns your base URL and will gave you codeIgniter root folder path. If you want to call image or file in another folder, you will have to pass path as a parameter to this function. site_ url( ): This function returns site url. For example Listing 16: Using site_url in view to return site URL.

  echo site_url( );

The code in Listing 16, will give you codeIgniter root folder path with “index.php”. current_url( ): This function would return the full pathof the page being currently viewed.

Listing 17: Using current_url( ) in view to return full path.

  echo current_url();

anchor( ): The anchor( ) function helps you create links that are portable from one environment to another. For example, to create a link to a contact_us page, you would simply pass two arguments to the anchor( )function: the URI followed by the link text.

Listing 18: anchor( ) function to create a link.

  echo anchor(‘welcome/contact_us’,‘Contact Us!’);

mailto( ): The mailto( ) function will help you send emails directly form a script and visible in view source.

Listing 19: Sending direct email using mailto( )

  echo mailto('', 'Click Here to Contact Me');

safe_mailto( ): The safe_mailto( ) function allows you to send emails directly from a script. This function encodes the link address from being harvested by spam bots.

Listing 20: Using safe_mailto( ) for sending email

  echo safe_mailto('', 'Click Here to Contact Me');

The funciton in Listing 20, would produce the encoded script in view source.

auto_link( ): This function changes URL and EMAIL to links, when given as a string parameter.

Listing 21: Changing URL and EMAIL to linke using auto_link( ).

  $string = auto_link($string, $type,$popup);

The function in Listing 21, took three parameters.

$string: for input string.

$type: Link type(‘email’, ‘url’ or ‘both’).

$popup: Whether to create popup links.

prep_url( ): This function will add http:// in the event that a protocol prefix is missing from a URL. Pass the URL string to the function like this as shown in Listing 22.

Listing 22: Usign prep_url( ) function to add http to URL.

$url = "";
  echo prep_url($url);

The code in Listing 22, will produce output like this

redirect( ): The redirect( ) function allows you to create redirects in case of different problems.This function first parameter is “uri segment”, you would give the link which you want to refresh or redirect, second is “location”, and third is “http responce code” .

Listing 23: Using redirect( ) function.

  if ($this- > session- > userdata(‘email’) != ‘’){
  redirect(‘admin/logout’, ‘refresh’);

In Listing 23, if the email address is not set correctly, the redirect( ) function will be called.


In this article, we have learned session library, CodeIgniter helpers, and how to load and use helper functions. Moreover, we created a form using CodeIgniter form helper. We understood the working of controllers and views. At the end, we discussed URL helpers and now you should be aware of their various functionalities. Our next step is to learn models, how to create and use them. Thanks for reading article hope you have enjoyed reading this article and got the concept.


Online user guide of CodeIgniter is available at

Software developer doing B.E in Computer Science at Hamdard university karachi. Have good skills in php, html, javascript and css.

What did you think of this post?
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!

> More info about MrBool Credits
You must be logged to download.

Click here to login