CodeIgniter: Tips & Tricks

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:

[cc lang=”php”]
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;
}
}
[/cc]

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

[cc lang=”php”]

[/cc]

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:

[cc lang=”php”]
$this->form_validation->set_rules(‘field_name’, ”, ”);
[/cc]

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:

[cc lang=”php”]
define(‘FULLPATH’, pathinfo(__FILE__, PATHINFO_DIRNAME));
[/cc]

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

  • Kivanc |

    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 😛

So, what do you think ?