How to Get URI Segment in PHP


The URL segments are used for many purposes in the web application. You can parse URL segment easily using parse_url() function in PHP. Here we’ll provide the example code to get URI segments and last URL segment using PHP.

Get URI Segments in PHP

Use following code to get URL segments of current URL. It returns all the segments of current URL as an array.

$uriSegments explode("/"parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

Usage:
When the current URL is http://www.example.com/codex/foo/bar.

echo $uriSegments[1]; //returns codex
echo $uriSegments[2]; //returns foo
echo $uriSegments[3]; //returns bar

Get Last URL Segment

If you want to get last URI segment, use array_pop() function in PHP.

$lastUriSegment array_pop($uriSegments);
echo 
$lastUriSegment//returns bar

Leave a reply