Create Custom URL Helper Function in CodeIgniter

In CodeIgniter, we all know that the project base URL is defined in application/config/config.php file. If project location is changed, you only need to change the $config['base_url'] value. The project base URL could get by calling base_url() method in CodeIgniter project. Like this, you can define the custom variable in application/config/config.php file and get the respective variable value from anywhere in CodeIgniter project.

create-custom-url-helper-function-in-codeigniter-by-codexworld

In this article, we’ll show the simple way to define a custom URL and getting the respective URL from custom URL function. Here we’ll define the public URL (where all the assets content would be stored) and public_url() function to get the project assets directory URL.

At First create a custom URL function. Open the system/helpers/url_helper.php file and create public_url() function.

/**
 * Public URL
 * 
 * File public URL, function created by CodexWorld.
 *
 * @access    public
 * @param   string
 * @return    string
 */
if ( ! function_exists('public_url'))
{
    function 
public_url()
    {
        
$CI =& get_instance();
        return 
$CI->config->config['public_url'];
    }
}

Open the application/config/config.php file and assign the Public URL in config array.

/*
|-----------------------------------------
| File Public URL
|-----------------------------------------
|
| URL to your assets root directory:
|
|    http://example.com/assets_dir/
|
*/
$config['public_url'] = "http://" $_SERVER['HTTP_HOST'] . "/assets/";

Example Uses

Here the example to displaying an image using custom URL function in CodeIgniter project.

<img src="<?php echo public_url(); ?>images/codex.png"  alt="">

Conclusion

Using this way you can define any custom variable and respective function for using globally in the project. Also, you can retrieve the config item without creating a custom function by using the following line of code.

$this->config->item('public_url');

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

Leave a reply

keyboard_double_arrow_up