Forum Moderators: coopster
There are various ways of enabling this, including mod_rewrite, ISAPI_rewrite and 404-handling. I'll not go into those here.
Standard operating process is:
I've seen, during this month alone, two cases of scripts which fail to check if the new URL calculated is unique, and one case in which the script just throws and error and asks the user to change their title.
A neat solution to this problem is to add numbers to the end of the textual part of the false filename. This a is long established practice with origins reaching back thousands of years.
Assume a database table `articles` containing `title`, `url`, and `text`. Of course, you might be writing physical files for a performance boost - if so, then change the database check below for file_exists()
First, calculate your ideal new URL, given $title, in this case by stripping out all characters which aren't a-z or 0-9 and replacing them with a - ("here: my title" -> "here-my-title"):
$url = preg_replace("/[^a-z0-9]+/i","-",$title); Don't add the extension yet, but we'll define it:
$extension = '.html'; Now, we'll set up a putative suffix of '':
$suffix = ''; We'll now write our test to check if the URL is available - and for as long as it isn't, we'll keep incrementing the suffix:
while (!mysql_num_rows(mysql_query("SELECT `url` FROM `articles` WHERE `url` = '".mysql_escape_string("$url$suffix$extension")."' ")) $suffix++; Now, go ahead and use "$url$suffix$extension" as your new URL to insert into the database.
Note the way in which this works. It is a valuable technique for many situations - at each point you create a test result and check it. Use of the while() loop with the! negation allows the test result to be modified at each pass. With minor modifications this simple structure in which the content of the while loop adjusts the test in the condition can be used for solving many kinds of problems.
This isn't the most efficient routine, but I think it's fine for most cases. After all, the greater part of the load on such a system typically comes from viewing, not from adding new entries.
If you don't want them named 'file.html' 'file1.html' 'file2.html' and prefer to miss out 'file1.html' then:
Change:
$suffix++; To:
{if ($suffix) $suffix++; else $suffix=2;}
so insted of you having my-title.htm, you will have 2007-07-13/my-title.htm
it is rather rare for an author to post an exact same title on the same day, as long as there are a handfull of authors on the same project/site.
in case of blogs, you modify your url to include the loginame/username/authorname in the url: mynick/date/title.htm or similar.