Using CodeIgniter URL class’s function, we can retrieve information from URI string. In this tutorial we are going to explain how we can use the URI class in CodeIgniter to retrieve information from URI segment.

Note: This class is initialized automatically so we do need to do it manually.

$this->uri->segment(n)

Segment function allow you to retrieve a specific segment form URI string where n is a segment number.Segments are numbered from left to right.For example,if  your URI like.codeigniter uri segment

By the above example URI segment function give result by n parameter.

echo $this->uri->segment(1);//it will print blog
echo $this->uri->segment(2);//it will print language
echo $this->uri->segment(3);//it will print php
echo $this->uri->segment(4);//it will print function

$this->uri->slash_segment(n)

slash_segment function allow you to retrieve a specific segment form URI string with slash and second parameter add slash to trailing and/or leading point. If the parameter is not used, added slash on trailing point. For example

echo $this->uri->slash_segment(1);//it will print blog/
echo $this->uri->slash_segment(2,'leading');//it will print /language
echo $this->uri->slash_segment(3,'both');//it will print /php/

$this->uri->uri_to_assoc(n)

uri_to_assoc function allow you to make associative array of key/value pairs from URI string.For example

http://www.domainname.com/index.php/blog/language/php/function
$temp=  $this->uri->uri_to_assoc(2);
//it will print associative array of key/value pairs
//NOTE: change parameter 2 to n based on your URI length

/**
Array ( [blog] => language [php] => function)
*/

$this->uri->assoc_to_uri()

assoc_to_uri function use for generating  URI from associative array.For example

$url_data=array ( [blog] => language [php] => functions);
$str = $this->uri->assoc_to_uri($url_data);
/**
it will Produces
blog/language/php/functions

*/

$this->uri->uri_string()

uri_string function use for generating string from complete URI. For example

http://www.domainname.com/index.php/blog/language/php/function
echo $this->uri->uri_string();
//it will return
/**
blog/language/php/function
*/

$this->uri->total_segments()

total_segments function return the total number of segments. For example

echo $this->uri->total_segments();//it will return 4

$this->uri->segment_array()

segment_array function returns an array containing the URI segments. For example

print_r($this->uri->segment_array());

/**  it will Produces
Array ( [1] => blog [2] => php[3] =>language [4] =>function )
*/
//Or you can use  like

$uri_data= $this->uri->segment_array();
foreach ($uri_data as $segment)
{
echo $segment;
echo '<br />';
}

Conclusion:

This was all about URI class in  CodeIgniter by using this we can perform different task by catching URI segment. Hope you like it, keep reading our other blogs