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));

When the current URL is

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);
$lastUriSegment//returns bar

Leave a reply