Tag Archives: codeigniter

CodeIgniter: Load View from Database (more or less)

I have seen a few people asking how to load a view from a database (or something other than a physical file in the “views” folder).

In my particular case, a client wants the ability to edit HTML and TEXT email templates. Without giving them direct access to editing the physical files, I decided to move the views being used for email to the database instead. Continue reading

How-To: Reload verification image using Codeigniter 2 CAPTCHA helper

Out of the box, CodeIgniter has a good CAPTCHA helper to use in your web applications. Here is a simple example of how to get a new CAPTCHA image without having to reload the page ūüėČ

Basic Controller

class Welcome extends CI_Controller {

    private $captcha_path = 'assets/img/captcha/';

    public function __construct()

    public function index()
        $captcha = create_captcha(array(
            'word'        => strtoupper(substr(md5(time()), 0, 6)),
            'img_path'    => $this->captcha_path,
            'img_url'    => $this->captcha_path
        $data = array(
            'captcha'        => $captcha
        $this->session->set_userdata('captcha', $captcha['word']);
        $this->load->view('welcome', $data);


The View (jQuery used for UI buttons and altering CAPTCHA image ‘src’ attribute)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/themes/blitzer/jquery-ui.css">
        text: false,
        icons: {
            primary: 'ui-icon-refresh'
        $(this).prev().attr('src', 'welcome/new_captcha?'+Math.random());
<?php echo $captcha['image']; ?>
<a href="#" id="new_captcha">Reload CAPTCHA</a>

Modified Controller Continue reading

Extending the CodeIgniter URI class to simplify pagination base_url option

In a lot of my controllers, I use pagination along with the HTML <base> tag’s href attribute for relative link URLs.

Example URL: http://www.domain.com/admin/users/index/pagination_offset

HTML Base tag: <base href=”http://www.domain.com/admin/”>

What this means, is I usually have to build pagination’s base_url option based on where I am and what information is being passed in the URI. A lot of times it ends up looking something like…

$this->load->library('pagination', array(
    'base_url'       => $this->uri->segment(2) . '/' . $this->uri->segment(3) . '/' . $this->uri->segment(4),
    'total_rows'     => $total_rows,
    'per_page'       => 20,
    'uri_segment'    => 4

What I decided to do what extend the core CodeIgniter URI class to provide a basic slice method to grab a chunk of the URI by applying PHP’s array_slice function to the segments property of the URI class. Continue reading

Improved database table structure for CodeIgniter sessions

I had a problem where CodeIgniter sessions stored in the database were creating multiple session_id’s (each time the session library was called) for the same user.

Here is how my session configuration is defined…

$config['sess_cookie_name']        = 'my-session';
$config['sess_expiration']        = 60*60*2; //2 hours
$config['sess_expire_on_close']    = TRUE;
$config['sess_encrypt_cookie']    = FALSE;
$config['sess_use_database']    = TRUE;
$config['sess_table_name']        = 'sessions';
$config['sess_match_ip']        = FALSE;
$config['sess_match_useragent']    = TRUE;
$config['sess_time_to_update']    = 300;

Here is the updated table structure…

  `session_id` varchar(32) NOT NULL default '0',
  `ip_address` varchar(16) NOT NULL default '0',
  `user_agent` varchar(255) NOT NULL,
  `last_activity` int(10) unsigned NOT NULL default '0',
  `user_data` text NOT NULL,
  PRIMARY KEY  (`session_id`)

My solution… First, I increased the user_agent field to 255 characters in length. Then, since session_id is always 32 characters in length, I reduced that from 40. If you have any other suggestions, feel free to leave a comment.

Hope this helps someone else having the same problem with CodeIgniter sessions that are being stored in the database ūüôā

Change CodeIgniter’s Form_validation error delimiters globally!

I have seen this question all over the web and am surprised that nobody has actually offered such a simple solution.

Anyway, here is a quick, simple and painless way to set CodeIgniter’s error delimiters (used by the Form_validation library) one time for your entire application. Create “application/libraries/MY_Form_validation.php” with the following contents… Continue reading

Easily load multiple views with CodeIgniter

It is not uncommon to load a common header, footer and other views in each controller. While this can be achieved like so…

$this->load->view('header', $header_data);
$this->load->view('content', $content_data);
$this->load->view('footer', $footer_data);

I wanted the ability to do the same thing with a single line of code. So I decided to extend the core Loader library by creating “application/core/MY_Loader.php” with the following code… Continue reading

Disable browser cache easily with CodeIgniter

I have a project where users are validated by session data. When the user logs out I destroy the session and redirect them to the log-in page, but this does not prevent them from clicking the browser’s “back” button, in which case they still see the data.

My first solution was to set headers with PHP’s header() function. Then I decided to use CodeIgniter’s setheader() function from the Output library (no real difference, just using CI methods when possible). Finally, I decided the best way to do this would be to extend the Output library itself. This way I am not repeating multiple function calls in each controller. Here is end-result… Continue reading

My ultimate .htaccess file for CodeIgniter 2.0

#Initialize mod_rewrite
RewriteEngine On
RewriteBase /

#Force "www" subdomain
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

#Re-route forbidden urls
RewriteCond %{REQUEST_URI} ^(system|application).* [OR]
RewriteRule ^(.*)$ index.php?/$1 [L]

#Re-route urls if file/directory does not exist
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

CodeIgniter Form Validation Callback Functions with Multiple Arguments

If you’re reading this you most likely already know that you can only send one argument to callback functions using CodeIgniter’s Form Validation Class. If you are not yet familiar with this feature/limitation, here is an example of how the callback works.

Here is our controller with a normal callback (_foo) and our multiple-argument callback function (_valid_login)… Continue reading

Validate email domain using PHP’s checkdnsrr with CodeIgniter

I recently noticed a bunch of garbage registrations for an existing client’s newsletter function written quite some time ago. After making a copy of the subscribers table and “cleaning” the data (proper-cased names, lowercased emails, etc), I started looking at ways to limit these automated registrations.

The client would not be happy with registration confirmation emails, so I decided to make a callback function for use with CodeIgniter’s Form Validation library. Since it was only needed in one location, this method made more sense to me than extending the main library.

Here is the function…

Continue reading