If you have done any web development, passing requests becomes an integral part of your code. Whether it is a session id, data to validate, or a view file to load you will most definitely end up passing one request or another. While working on my framework (which uses the model-view-controller design pattern), I decided to pass the controller, which the framework will load, through the URL. Since the controller’s primary purpose is to handle incoming http requests, I also passed a “view” parameter through the URL (which the controller will delegate accordingly). At this point, my URLs became unattractive index.php?module=Blog&view=index, which in todays world, of Web 2.0 sex appeal and search engine optimization, is just unacceptable. To circumvent the unsightly link, many developers choose to use mod_rewrite and define expressions in a .htaccess file. This is a perfectly legitimate practice for those of you who have mod_rewrite enabled on their server (and actually understand the rules). As an alternative, PHP’s $_SERVER['REQUEST_URI'] provides a cleaver solution.
What does $_SERVER['REQUEST_URI'] provide us with? Essentially, everything after the domain name. So if our URL is http://www.example.com/index.php?module=Blog&view=index, our URI is index.php?module=Blog&view=index. Moreover, if our URL is http://www.example.com/index.php/Blog/index, our URI is index.php/Blog/index. Using this, we can simply manipulate the URI to process incoming requests. First, we want to explode the URI at the file name, in my case it is index.php.
1 |
$requests = explode("/index.php/", $_SERVER['REQUEST_URI']);
|
$request is now an array whose first element is everything before and including index.php, and whose second element is everything after index.php. By manipulating $requests[1] we can use that data as our data.
1 2 |
$requests = explode("/index.php/", $_SERVER['REQUEST_URI']);
$uri = explode('/', $requests[1]);
|
The $uri array now contains all our disguised requests, which we can use in the same way as a $_GET request (with the exception of a sexier URL).
With three lines of code we have transformed a ugly looking URL http://www.example.com/index.php?module=Blog&view=index to http://www.example.com/index.php/Blog/index (a URL the most avid Web 2.0 gurus would find acceptable).

January 10th, 2010 at 12:19 am
Thanks. Just found your blog and it’s definately gonna get book marked.
/Marcus
January 10th, 2010 at 12:23 am
No problem Marcus. Glad you found it useful.