Creating clean URIs with PHP
UPDATED to fix a broken link and correct some technical issues.
I recently switched from dynamic URIs to faux-static ones. Here’s how
to do the same on your site.
I’m going to assume that you’ve already got your own PHP/MySQL-driven publishing system in place, and that you currently use
dynamic URIs on your site.
Step one: Change your URIs
I use ‘perma-links’ on this site, as most ‘blogs do. The perma-link gives site visitors a target if they want to link to a specific entry on your site. If you use dynamic URIs, your perma-links are probably structured like this: filename.php?id=000.
Let’s clean up that URI: filename.php?id=000 will become
filename.php/000. You’ll notice that we’ve dropped the question mark, and the variable name (id).
Step two: Get the new URI
Next, you’ll need to modify the code on your template (in this
example, filename.php) so that it processes the new URIs. But first, you’ll need to get the user-requested URI by using:
$_SERVER['REQUEST_URI'].
$_SERVER['REQUEST_URI'] will return the location of the file on your server relative to your web root. In other words, if a visitor requested http://www.tiffanybbrown.com/example.php/200, the result of $_SERVER['REQUEST_URI'] would be /example.php/200.
Step three: Process the URI
In order to ‘process’ the URI, we’re going to use the explode() function. The code>explode() function "splits a string by a string" and creates an array variable.
In this example, we're going to split the entire request URI of the string by the PHP script name, and save it as a variable:
$entry=explode("/example.php/", $_SERVER['REQUEST_URI']);
The first parameter says where to split the string. The second parameter is the string to split. In this case, it's the request U R I. Note: you could also use / as the split point.
Now you can use each portion of the U R I by referring to the array.
60-second introduction to arrays:
Arrays are a special type of variable that holds a group of associated items. Think of an array as books on a shelf. The entire collection would be $shelf. To use the first book on the shelf, you'd use $shelf[0]. For the second book $shelf[1], and so on (Remember in programming, counting starts at zero).
To get the unique identifier of the entry, then, we'd do this:
$id=$entry[1];
Then you can use the variable $id in your SQL query. If you're using numeric identifiers, don't forget to check that the requested entry is a valid numeric string. And of course, use quotes around properly escape all variables to protect yourself from SQL injection attacks.