Using CodeIgniter URI core class
Generally within CodeIgniter Hooks, we need to load/instantiate the URI core class to reach the methods.
- For
post_controller_constructor
,post_controller
, ... hooks, we can get the CodeIgniter super object and use use theuri
class:
# Get the CI instance
$CI =& get_instance();
# Get the third segment
$CI->uri->segment(3);
- But for
pre_controller
hook, we don't have access to CodeIgniter super object So we have to load the URI core class manually as follows:
# Load the URI core class
$uri =& load_class('URI', 'core');
# Get the third segment
$id = $uri->segment(3); // returns the id
Using pure PHP
In this approach you can use $_SERVER
array to fetch the URI segments as:
$segments = explode('/', trim($_SERVER['REQUEST_URI'], '/'));
$controller = $segments[1];
$method = $segments[2];
$id = $segments[3];