URL rewriting using PATH_INFO
There are many reasons to rewrite a website’s URLs – for SEO purposes, better organisation or simply so that the URLs look nicer. The most popular way to do this on Apache servers (and on all servers it has been ported to) is to use mod_rewrite, a server configuration option that uses regular expressions to rewrite URLs dynamically. However, mod_rewrite isn’t always available – you could be using a different server such as Lighttpd, or may simply not have rights to create
.htaccess files on a shared host. For such situations, an alternative is needed, and one such alternative is the use of the
PATH_INFO server variable.
PATH_INFO method works by appending more information after the script name when constucting a request. For example, a site may have a page
/index.php, which can be requesed over HTTP. However, if a request is made to
/index.php/foo/bar instead, the webserver will still understand that to want
/index.php, but the extra information remains in the path, and can be retrieve in PHP using the
$_SERVER['PATH_INFO'] (or, if that doesn’t work,
$_SERVER['REQUEST_URI']) superglobal index. So, for example, if the URL structure was set up so that the page at
index.php could have the following code:
<?php $page = pop(explode("/", $_SERVER['PATH_INFO'])); include("$page.php"); ?>
That’s all there is to it, however if needed the method could be extended to include multiple variables, etc., or use the retrieved path info to fetch data from a database. While this method isn’t as elegant or nice-looking as a server-rewrite solution like
mod_rewrite, it is still better than nothing, and is portable between all environments.