URI
Clean URIs with PHP, part two
Submitted by Arancaytar on Wed, 06/28/2006 - 23:59 – No commentsThis post is not going to go into much detail - I have my last lectures tomorrow, before the exams next week, so I really have other things on the horizon, but I can give a brief run-down of what else is involved in using PHP to make clean URIs.
The Content Handler
In the last post, I explained how to set up your .htaccess file so that all content under a certain directory level (say "/wiki") is handled by a certain PHP script. The next issue is how to set up this PHP script so it can actually serve content.
The PHP script needs to take the requested URI and return the resource. The URI is translated into a file through a lookup table in a MySQL database.
Lookup table
The lookup table can be surprisingly minimal. At the basic level, only two fields are required: The alias, and the corresponding filename.
CREATE TABLE alias_lookup ( alias VARCHAR (64) PRIMARY KEY, filename VARCHAR (64) NOT NULL );
The PHP script
Note: This is really just an example. Several things are unrealistic in practice; for example, the mysql query is potentially vulnerable to injection attacks.
// the directory of this content handler $handler_dir = '/main/'; $request = $_SERVER['REQUEST_URI']; // lookup $link = mysql_db_connect( {your database access info here} ) $sql = "SELECT filename FROM alias_lookup WHERE CONCAT('$handler_dir',alias) = '$request';"; $res = mysql_query($sql,$link); $row = mysql_fetch_array($res); $filename = $row[0]; // include if ($filename) { if (file_exists($filename) include($filename); // resource removed else header("Status: 401 Gone"); } // alias doesn't exist. else header("Status: 404 Not Found"); exit; ?>
Of course, you can do a lot more with this: Setting different content types and handling graphics as well as text, even including PHP programs that are themselves content handlers for resources lying further down the directory tree. In one website I just made, I use a regular expression match to replace certain links and add a visitor counter to html files before displaying them on the page - without having to change the original files!
- Arancaytar's blog
- Add new comment
- 3350 reads



