Jun
23
2011

PHP Get URI Segment(s)

Here is a set of two php functions that I use regularly to quickly get a specific URI segment or return all segments available.

These are very helpful if you have written or are writing your own custom SEF urls

<?php

function getUriSegments() {
	return explode("/", parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
}

function getUriSegment($n) {
	$segs = getUriSegments();
	return count($segs)>0&&count($segs)>=($n-1)?$segs[$n]:'';
}

?>

How to use:

<?php

// if the url is http://www.timwickstrom.com/foo/bar/wow

echo getUriSegment(1); //returns foo
echo getUriSegment(2); //returns bar

print_r(getUriSegments()); //returns array(0=>'foo', 1=>'bar', 2=>'wow')

?>

Happy Coding!

3 Comments + Add Comment

  • thanks dude! :)

    Thumb up 2 Thumb down 2

  • Very nice, much appreciated.

    Thumb up 2 Thumb down 0

  • Excellent post. I was searching for something different completely,
    but stumbled on your site. I am glad I did. Thank you for sharing
    useful information. Thank you and best of luck.

    Thumb up 0 Thumb down 0

Leave a comment

Show/Hide Footer Actions

Status: Available for your project.