Fetch URI Segments

Still many people using query string / get method for their URL to getting the value from the user , but these query strings are not Search engine friendly , To create a searchengine friendly url you can make use of URI segments

asvignesh.in/blog_post?title=post_name Instead we can use like asvignesh.in/blog_post/post_name

I explain you how to fetch the URI segments

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]:”; //if uri segment us available then return uri else return ‘null’
}
?>
<?php
// if the url is http://asvignesh.in/foo/bar/wow
echo getUriSegment(1); //returns foo
echo getUriSegment(2); //returns bar
var_dump(getUriSegments()); //returns array(0=>’foo’, 1=>’bar’, 2=>’wow’)
?>

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from

Subscribe now to keep reading and get access to the full archive.

Continue reading