Ever wondered how a CMS like WordPress creates those pretty URLs that resemble directory structures on the fly?Ever wondered if you could do the same thing with your own website or web app? Well you can, and it’s ridiculously simple.
Step 1: You need to edit your .htaccess file to incorporate some mod rewrite rules. This is the code that we’re going to use (the same code that WordPress uses):
RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /yourcode.php [L]
What this does is capture the “filenames” (really just a URI string that comes after your site root), and pass them on in an array to the file of your choice, “yourcode.php” in this case. It does all this without changing the URL on the user’s end. So now all we have to do is pick up those variables in our PHP code. We’ll do that with this code in yourcode.php :
$uri = $_SERVER['REQUEST_URI']; $vars = explode('/', $uri);
So now we’ve captured the elements of the permalink in our array $vars, starting with the second array object, $vars[1]. The first array object, $vars[0] will return as blank. So let’s suppose the user is trying to go to this address:
http://www.yoursite.com/someuser/profile
$vars[1] will be “someuser”. $vars[2] will be “profile”. We can then use that information like so:
$user = $vars[1]; $page = $vars[2];
… and then use those variables to determine what data we output to the browser.
Easy as pie.
Date: Wednesday, December 9th, 2009
Category: Web Dev