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
Sep 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
Dec 9, 2010
#2
hello thanks for share this relative urls that help me alot, but i have problem, i use redirect in my php but it just show Refresh: 0;url=../../ is there any method to fix redirect ?
UesugiChezt
Jul 24, 2013
#3
I know a little bit about relative path. Suppose, I have a project on codeigniter. There are 4 controller such as with function name:

1. Admin->index,profile,add_student,edit_marks,make_admin,
2. Teacher->index,add_marks,update_marks
3. Student->index,view_teacher,view_result
4. Guest->index,view_Student, view_marks,view_result
From these, How can I use them as relative path ?Remind it,some times I go one controller to another controller, such as profile,view_marks is a common function for all, so every one access it.

For images or file can I use relative path ? Then,Suppose I have a image at root folder as ->root_folder/template/images/a.png. How can I use it as relative path ?

Really, I need the core knowledge of relative path with application in codeigniter.

This question is available at http://stackoverflow.com/questions/24306733/how-can-i-use-relative-path-in-codeigniter
kabir
Jun 19, 2014
#4
Please How can i add www. to the name of my website using codeigniter eg:
from: example.com
to: www.example.com
Ibrahim
Aug 6, 2014
#5