Mohammad Rashidi
Mohammad Rashidi

Reputation: 35

add custom function to Codeigniter config such as site_url() & base_url()

we need to have a new function such as base_url() , named main_site_url() to being able to use it exactly as the same as site_url().

I've just added this to main config file in application/config:

$config['main_site_url'] = 'http//iksna.com/';

and this code to /system/core/config.php

/**
 * Main Site URL
 * Returns main_site_url . index_page [. uri_string]
 *
 * @access  public
 * @param   string  the URI string
 * @return  string
 */
function main_site_url($uri = '')
{
    if ($uri == '')
    {
        return $this->slash_item('main_site_url').$this->item('index_page');
    }

    if ($this->item('enable_query_strings') == FALSE)
    {
        $suffix = ($this->item('url_suffix') == FALSE) ? '' : $this->item('url_suffix');
        return $this->slash_item('main_site_url').$this->slash_item('index_page').$this->_uri_string($uri).$suffix;
    }
    else
    {
        return $this->slash_item('main_site_url').$this->item('index_page').'?'.$this->_uri_string($uri);
    }
}

// -------------------------------------------------------------

but now, it is not accessible by: main_site_url();

is it accessible by: $this->config->main_site_url();

i have this error when is use main_site_url();

error:

Call to undefined function main_site_url()

Upvotes: 2

Views: 2763

Answers (2)

Sarvap Praharanayuthan
Sarvap Praharanayuthan

Reputation: 4360

You can create your own by the following way:

Step 1:

In you application/config/config.php add this, $config['main_site_url'] = 'http//iksna.com/';

Step 2:

In system/core/Config.php add a new function main_site_url() like base_url(), site_url() which are already defined there:

public function main_site_url($uri = '', $protocol = NULL)
{
    $main_site_url = $this->slash_item('main_site_url');

    if (isset($protocol))
    {
        if ($protocol === '')
        {
            $main_site_url = substr($main_site_url, strpos($main_site_url, '//'));
        }
        else
        {
            $main_site_url = $protocol.substr($main_site_url, strpos($main_site_url, '://'));
        }
    }
    return $main_site_url.ltrim($this->_uri_string($uri), '/');
}

Step 3:

Now add the following code in system/helpers/url_helper.php

if ( ! function_exists('main_site_url'))
{
    function main_site_url($uri = '', $protocol = NULL)
    {
        return get_instance()->config->main_site_url($uri, $protocol);
    }
}

Now you can use main_site_url() anywhere in your controllers, libraries and views just like base_url(), site_url() etc.

Upvotes: 2

dhruv jadia
dhruv jadia

Reputation: 1680

Go to

/system/application/libraries

Create one file named

custom_function.php

add function main_site_url inside custom_function.php

call function in controller file using

$this->custom_function->main_site_url();

Upvotes: 0

Related Questions