How to set proper dynamic base url in CodeIgniter 3

This post will show you how to get current url and base url in codeigniter. In codeigniter the term, Current URL refers to the complete URL of the current webpage being loaded and Base URL is the domain name or path to the application root (on localhost)

PHP Code igniter comes with URL Helper to assist you in working with application URLs. This helper contains bunch of methods to access URLs and in order to use them, you must first load the URL helper either inside controller or auto load it using autoload.php file.

You will need to set your base URL in application/config/config.php

To load URL Helper use this statement,

$this->load->helper('url');

Or add this below line to ‘config/autoload.php

$autoload['helper'] = array('url');

Open config.php and find below code

$config['base_url'] = '';

Now Replace With 

$root = (isset($_SERVER['HTTPS']) ? "https://" : "http://") . $_SERVER['HTTP_HOST'];
$root .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
$config['base_url'] = $root;

OR

defined('BASE_URL') OR define('BASE_URL', (is_https() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . dirname($_SERVER['SCRIPT_NAME']) . '/');
$config['base_url'] = BASE_URL;
RH Suman
RH Suman
Articles: 64

Newsletter Updates

Enter your email address below to subscribe to our newsletter

Leave a Reply