| Subcribe via RSS

PHP Function for URI and URI Segments

September 3rd, 2009 Posted in Code, PHP

Here's a function I wrote to parse through the URI to get segments. I wrote it to use with CodeIgniter to get URI segments before they had been altered and "-" gets changed to "_". It can be used in any application.

PHP:
  1. <?php
  2. function uri($segment=NULL, $qs=false){
  3.     $uri = $_SERVER['REQUEST_URI'];
  4.     if(!$qs || $segment !== NULL){
  5.         if(strpos($uri, '?')){
  6.             list($uri, $query) = explode('?', $uri);
  7.         }
  8.         if($segment !== NULL){
  9.             if(is_string($segment)){
  10.                 if($segment != 'last'){
  11.                     return ( strlen($uri)>= strlen($segment) && substr($uri, 0, strlen($segment)) );
  12.                 }
  13.             }
  14.             $str = trim($uri, '/');
  15.             $segments = (strpos($str, '/')) ? explode('/', $str) : array($str);
  16.             $ttl = count($segments);
  17.             if(is_string($segment) && $segment == 'last'){
  18.                 $seg = array_pop($segments);
  19.             } elseif($segment <= $ttl){
  20.                 if($segment <0) $segment = $ttl - abs($segment) + 1;
  21.                 $seg = $segments[$segment-1];
  22.             } else {
  23.                 return '';
  24.             }
  25.            
  26.             return $seg;
  27.         }
  28.     }
  29.     return $uri;
  30. } ?>

Usage:

PHP:
  1. // uri:  http://www.mysite.com/some-controller/some-method/
  2.  
  3. echo uri();
  4. // displays: /some-controller/some-method/
  5.  
  6. echo uri(2);
  7. // displays: some-method
  8.  
  9. // Pass true into 2nd paramater ($qs) to display Query String with URI
  10. // uri:  http://www.mysite.com/some-controller/?foo=bar&bar=foo
  11.  
  12. echo uri(NULL, true);
  13. // displays: /some-controller/?foo=bar&bar=foo

One Response to “PHP Function for URI and URI Segments”

  1. akira Says:

    Nice article thank you for sharing!


Leave a Reply

Preview: