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!

2 Comments + Add Comment

  • thanks dude! :)

    Thumb up 1 Thumb down 2

  • Very nice, much appreciated.

    Thumb up 1 Thumb down 0

Leave a comment

Show/Hide Footer Actions

Status: Available for your project.