How to set proper dynamic base url in Codeigniter 3

RH Suman
June 20, 2022

41

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)
How to set proper dynamic base url in Codeigniter 3

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;

Tags

Codeigniter Codeigniter 3 base_url PHP

Subscribe

Get Updates

Subscribe our newsletter to get the last update into your inbox!

Please insert email address.

Recommended Posts