CodeIgniter: Tips & Tricks

by Vicente Russo Neto on March 10, 2009

Hello, Today I’ll post few modifications I use on every CI project. First, on the “url_helper“, I made this modification oon base_url() function:

1
2
3
4
5
6
7
8
9
10
if ( ! function_exists('base_url'))
{
    function base_url($link=FALSE)
    {
        $CI =& get_instance();
        $baseUrl = $CI->config->slash_item('base_url');
        if ($link===TRUE) $baseUrl .= $CI->config->slash_item('index_page');
        return $baseUrl;
    }
}

This allow me to use the base_url() function to work with and without the index.php. Sometimes you don’t know where your project will be hosted, and if the host supports mod_rewrite. In this case, on your links (those with index.php/controller) you just put

1
<?=base_url(TRUE)?>

and you will get the index.php or not, depending on your configuration, on config.php. If I use the TRUE parameter, the “index.php” string will be inserted before the controllers. Of course, you can alter the function to something like base_url(‘link’), or base_url(1), or anything you like. I don’t like to mess with the CI Core, so I saved this new helper on application/helpers directory.

Another Tip. This is very simple. Using the form validation, when I have a not required field, it isn’t repopulated with set_value() function if you don’t set any rules for the field. But if you set a blank rule, it will work:

1
$this->form_validation->set_rules('field_name', '', '');

When I use upload class, sometimes I have to delete the file when I change the file on database. And then It’s a good thing to use the absolute path when deleting, so I made a small constant declaration to set my root folder, the folder with index.php inside. In the index.php, add this line on bottom of the constant declarations:

1
define('FULLPATH', pathinfo(__FILE__, PATHINFO_DIRNAME));

Now, my FULLPATH constant is set with my base directory. Hope this can be usefull to someone. ;)

Did you like this? Share it:

{ 2 comments… read them below or add one }

Kivanc May 20, 2009 at 11:51 am

try site_url() helper function for base_url() with index.php. site_url() returns your base url with index file which can set in config.php. ;) Tanks for this post.Sorry for my english :P

sibel kekilli November 1, 2010 at 1:35 am

adamsiniz la siz tsk ettim ricalarimi sunarim.

Leave a Comment