Relative URLs with CodeIgniter

Using CodeIgniter pretty URLs while having relative paths in the generated HTML.

How it works

This hook updates base_url config item depending on the current URL. For

/movies/view/125

base_url will be set to

../../

So

site_url('css/styles.css')

will generate

../../css/styles.css

Enable hooks

system/application/config/config.php

$config['enable_hooks'] = TRUE;

Declare hook

system/application/config/hooks.php

// set base url
$hook['post_controller_constructor'][] = array(
	'class' => '',
	'function' => 'rewrite_base_url',
	'filename' => 'uri.php',
	'filepath' => 'hooks'
	);

The hook

system/application/hooks/uri.php

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 
function rewrite_base_url()
{
	$n = count(explode('/', uri_string())) - 2;
 
	$str = '';
	for ($i=0; $i < $n; $i++)
	{ 
		$str .= '../';
	}
 
	$CI =& get_instance();
	$CI->config->set_item('base_url', $str);
}
 
/* End of file uri.php */
/* Location: ./system/application/hools/uri.php */

Extra

 

Feedback

"Relative URLs with CodeIgniter" Unfortunately this doesn't work for me. It's always putting "index.php" instead of "../", so relative address is ruined. Maybe you have any suggestion why is this happening? I've tryied with typical url/controller/function/params/, also with different changed routes and it's all wrong. Have any idea why?
Jerry
September 4, 2009
#1
/**
* Detect relative url
*
* @param string $ex
* @return string
*/
function relative_path($ex = './')
{
$uri = uri_string();
$url = '';
for($i = 1; $i < substr_count($uri, '/'); $i++)
{
$url.= '../';
}

return $ex . $url;
}
quangpd@live.com
December 9, 2010
#2