This is how codeigniter does it, straight from the git repository:
https://github.com/EllisLab/CodeIgniter
CodeIgniter / application / config / config.php
/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
|
| URL to your CodeIgniter root. Typically this will be your base URL,
| WITH a trailing slash:
|
| http://example.com/
|
| If this is not set then CodeIgniter will guess the protocol, domain and
| path to your installation.
|
*/
$config['base_url'] = '';
CodeIgniter / system / core / Config.php
/**
* Class constructor
*
* Sets the $config data from the primary config.php file as a class variable.
*
* @return void
*/
public function __construct()
{
$this->config =& get_config();
log_message('debug', 'Config Class Initialized');
// Set the base_url automatically if none was provided
if (empty($this->config['base_url']))
{
if (isset($_SERVER['HTTP_HOST']))
{
$base_url = (is_https() ? 'https' : 'http')
.'://'.$_SERVER['HTTP_HOST']
.substr($_SERVER['SCRIPT_NAME'], 0, -strlen(basename($_SERVER['SCRIPT_NAME'])));
}
else
{
$base_url = 'http://localhost/';
}
$this->set_item('base_url', $base_url);
}
}
You should provide a base url in the config file, I presume this will then get autoloaded by codeigniter and the base_url() will return this value.
Whenever config.php gets instantiated it checks to see if the base url has been configured in the config.php, if it hasn't it will try and guess by checking the host, protocol base name of the script etc. Then the set_item method is called, which would set $config['base_url'] to whatever the logic above has determined to be the base url