How to Get URI Segment in PHP

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

Get URI Segments in PHP

Use the following code to get URL segments of the current URL. It returns all the segments of the 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

keyboard_double_arrow_up