Search Engine Friendly URLs with PHP

Nov 11, 2008 | Tags: SEO, PHP | del.icio.us del.icio.us | digg Digg

4. The Wrapper Script

With the previous .htaccess configuration, index.php now serves all non-static requests. The script performs a very simple task, it retrieves the filename being requested, get the article and display.

Listing 1: index.php

  1. <?php
  2. require_once 'connection.php';
  3.  
  4. /* get requested page */
  5. $dir  = dirname($_SERVER['PHP_SELF']);
  6. $page = basename(str_replace($dir, '', $_SERVER['REQUEST_URI']));
  7.  
  8. /* if empty display the homepage, otherwise display the page */
  9. if (empty($page)) {
  10.     require 'home.php';
  11. } else {
  12.     display_page($page);
  13. }
  14. ?>

If the filename is empty, then the request URL must be http://yourdomain.com and this should display your homepage. Otherwise it displays the article by calling display_page() function.

Listing 2: Function to display the page

  1. function display_page($page) {
  2.     /* get article */
  3.     $sql = "SELECT id FROM articles WHERE filename='$page'";
  4.     $res = mysql_query($sql);
  5.    
  6.     /* if not found, display 404 error */
  7.     if (mysql_num_rows($res) == 0) {
  8.         die('404 - Page Not Found');
  9.     } else {    
  10.         $row = mysql_fetch_object($res);
  11.     }
  12.    
  13.     $_GET['id'] = $row->id;    // setup query string manually
  14.     require 'article.php';    // call the 'real' script
  15. }

The function retrieves the article ID from database. If no article matches the filename being requested, it displays a HTTP 404 error. The query string ($_GET) is assigned manually and article.php is loaded. This trick makes article.php 'thinks' it was called with:

http://yourdomain.com/article.php?id=<Article ID>

Put the function above inside index.php. The script is very simple, isn't it?