[php] Simulating file system URI's

Status
Not open for further replies.

litewarez

Active Member
1,367
2008
1
0
In your htaccess use like:

Code:
    <IfModule mod_rewrite.c>
        RewriteEngine On
        #Rewrite the URI if there is no file or folder
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)$ index.php?/$1 [L]
    </IfModule>

Then in your PHP Script you want to develop a small class to read the URI and split it into segments such as

PHP:
    class URI
    {
       var $uri;
       var $segments = array();
    
       function __construct()
       {
          $this->uri = $_SERVER['REQUEST_URI'];
          $this->segments = explode('/',$this->uri);
       }
    
       function getSegment($id,$default = false)
       {
          $id = (int)($id - 1); //if you type 1 then it needs to be 0 as arrays are zerobased
          return isset($this->segments[$id]) ? $this->segments[$id] : $default;
       }
    }

Use like

Code:
http://mysite.com/posts/22/litewarez-shows-mvc-style-uri-access
PHP:
    $Uri = new URI();
    
    echo $Uri->getSegment(1); //Would return 'posts'
    echo $Uri->getSegment(2); //Would return '22';
    echo $Uri->getSegment(3); //Would return 'litewarez-shows-mvc-style-uri-access'
    echo $Uri->getSegment(4); //Would return a boolean of false
    echo $Uri->getSegment(5,'fallback if not set'); //Would return 'fallback if not set'

This way you can have clean urls as long as your expecting your params to be in the right order

Example of usuage in daily use

PHP:
switch($Uri->getSegment(1))
{
   case 'home':
   case 'index':
   default:
      echo 'I am Index';
   break;
   case 'post':
      if($Url->getSegment(2) != false) //We have id
      {
           echo sprintf('Showing post with id of %d',$Uri->getSegment(2));
      }else
      {
          echo 'Bad URI, Expecting id but got nothing.';
      }
   break;
}
 
Status
Not open for further replies.
Back
Top