URL rewriting let you hide all your ugly variable ridden URLs and instead present to the world clean, static URLs. For example (taken from ozziebuy.com.au), the URL:
http://www.ozziebuy.com.au/document.php?Filename=how_to_register
can take the form:
http://www.ozziebuy.com.au/how_to_register.htm
There are many advantages to using dynamic URLs. As they let your webpages appear as static HTML pages, search engines are more likely to index them (some search engines get jittery at indexing dynamic pages). They're more intuitive and user-friendlier for users. It allows you to put all your content into a database and greatly reduces the number of PHP pages to maintain (I'm a big fan of separating content and code). And crucially, it allows you (or your clients) to edit your website via a web based content management system rather than depending on HTML editors and ftp programs.
Sold to the idea yet? In this tutorial, I'll reduce an entire HTML website to a single PHP page. The first step is to create a MySQL table 'page' that will store your webpage content and for the sake of this exercise, insert one sample page:
CREATE TABLE `page` (
`PageId` int(11) NOT NULL auto_increment,
`Title` varchar(100) NOT NULL default '',
`Filename` varchar(30) NOT NULL default '',
`Content` text NOT NULL,
PRIMARY KEY (`PageId`)
) TYPE=MyISAM PACK_KEYS=0 AUTO_INCREMENT=20 ;
INSERT INTO page ( Title , Filename , Content )
VALUES ( 'Homepage', 'index', 'Content to go on homepage');
|
Next is to create a new text file and copy and paste the following content. Then save the text file as .htaccess (note - it mustn't have a .txt extension):
.htaccess
RewriteEngine on
RewriteRule ^([0-9a-zA-Z-_]*).htm$ index.php?Filename=$1 [L]
|
What this does is use a regular expression ^([0-9a-zA-Z\-\_]*).htm$ to look for any webpage that takes the form filename.htm. It then extracts the first part of the filename (whatever is in front of the period) and loads instead a page index.php?Filename=$1 where it replaces the $1 with the first part of the filename. In other words, if you visited the URL www.ozziebuy.com.au/how_to_register.htm, the regular expression would extract how_to_register and instead load the page www.ozziebuy.com.au/document.php?Filename=how_to_register. Now we need the webpage index.php:
index.php
// include and instantiate a database class
// see http://www.tipsntutorials.com/tutorials/PHP/76/ for more code on this
include ('includes/database.php');
$db = new Database;
// if no Filename is defined, send them to the homepage (alternatively you could send them to an error page)
if (!isset($_GET['Filename']) || !$_GET['Filename'])
$Filename = 'index';
else
$Filename = $_GET['Filename'];
// retrieve page content from database
$Query = "SELECT * FROM page WHERE Filename = '$Filename'";
$db->query($Query);
// only show content if we found something
if ($db->numRows())
{
// display title and content of this page
$db->singleRecord();
echo "<h1>".$db->Record['Title']."</h1>rn";
echo $db->Record['Content'];
} // end if we have page content
else
{
echo "<h1>Page Error</h1>rn There is no page at this address.";
} // end if we have no page content
|
Apologies but I use a database class explained in another tutorial for all my database functions (saves me repeating lots of code). If no Filename is specified in the URL, I assume one myself - 'index' in this case. Of course, you would have to have a page in your database with Filename 'index' for this to work. Alternatively you might want to send them to an error page or sitemap. Then it's a simple matter of finding the page in the database that matches the filename. If a page is found, display the title and content. If not, display an error message. And there you have it - all your HTML pages reduced to a PHP page, a .htaccess file and a MySQL database. Now all you have to do is whip up a content management system... easy! :-)
Comment by Rhys on 2007-06-17
Thank you for this tutorial. The idea of simplifying the URL to be more user friendly, and keeping things simple with a database is exciting. This should improve my websites. Thanks again!!
Comment by mbtshoesmasai on 2010-07-29
You select MBT Shoes to wear without reason because of its large charm. The health care of MBT Footwear is its advantage. MBT Shoes Clearance with soft and smooth surface is popular exercising shoes in daily life. Discount MBT Shoes can exercise your muscle to make you become the focal point in your office or other business occasions. MBT Shoes Cheap are made of high quality Nappa leather with a lasting effect. The natural unstability of MBT Masai Shoes compels the torso to keep body balance and stimulates small muscles around spine joint for a protection. As a fitness equipment, called Medical Shoes, MBT Outlet can effectively exercise small muscles around joints, strengthen muscles strength, and burn more fat. your cheerful experience and exercise benefits when you are walking with MBT Sandals can effectively treat obesity. At the same time, MBT Womens Shoes heel with 5 centimeters height can make you look taller. Wearing MBT Walking Shoes can reduce the pressure on knee and hip joints. Now MBT pushes out all kinds of shoes such as MBT Lami, MBT Changa, MBT Kaya and so on.
Welcome to our website: http://www.mbtshoesmasai.com
Comment by Coach Handbags on 2010-07-30
In recent years, Coach handbags has indeed built up quite a reputation and enjoys increasing popularity with consumers. With its popularity, Coach Bags become the most preferred brand throughout the world. Gucci Handbags are the obvious choice for many fashion conscious business women and those with a preference for timeless
oakley sunglasses classic styles and they wear so well and go with nearly everything in your closet.This bag is really worth owning.Coach Wallets was on the Chinese market for nearly 50 years. You can even see older people carry a coach starting line handbag.
Cheap Coach Purses Coach Bags are excellent for high quality and low price. These bags are more and more what people want.As Coach Outlet you smart crocodile, Caiman fuscus Coach Crossbody Bags crocodile clutch his last, which has five versions to choose from: orange,Chanel Handbags brown, gold, black, dark silver to make. Coach Op Art Bags The five drawings of the Viper clutch are per kart.
You will get more results out of your workouts - MBT have technology in the sole design that make your working more efficient and burn more calories. mbt outlet With every step, the instability activates Cheap MBT Shoes your muscles and the whole body is stimulated as your walk more and more.mbt shoes outlet have a curved pivot sole that copies walking on soft moss. The sole turns even, flat ground into uneven terrain. The discount mbt shoes challenges the muscles to work harder with every step you take. The unique curved sole works by providing instability and makes the muscles of your body more engaged and also helps burn more calories.MBT Sandals MBT VOI Shoes
MBT Salama Sandal
MBT Habari Sandal
MBT Fumba Sandals
Comment by philips on 2010-06-18
nice post,
but, what if i want database queries based on primary key (page id) instead of filename, cos i think it\\\\\\\'s bad practice to query based of title, filename, or something that\\\\\\\'s not a primary key.
i\\\\\\\'ve found solutions for this:
the URL goes something like this:
http://www.example.com/article/12/title-here
but i don\\\\\\\'t want to display id, so the url would look like this:
http://www.example.com/article/title-here
how can i do this...???
thx in advance!
|