: Help with URL Rewrite I have a page that selects some info from a database and displays it with a link to a second page that uses the result to query the database, something like this: $sel=mysql_query("select
I have a page that selects some info from a database
and displays it with a link to a second page that uses
the result to query the database, something like this:
$sel=mysql_query("select id, title from thetable ");
while($row=mysql_fetch_array($sel))
{
$id=$row['id'];
$title=$row['title'];
echo "<a href='more.php?id=$id'>$title</a>";
}
The issue is, in the more.php page, instead of more.php?id=5 to show in
the address bar, I want something like more/title
Secondly, as it obtains in most sites, I want the link on the referring page
to show this friendly url on mouse hover not the more.php?id=5
And I notice in most sites some words like 'a', 'and', 'the' etc are usually
removed from the url title(even if there originally), moreover how does one
handle the situation where more than one record have the same title.
How does one go about achieving this url rewrite with htaccess or whatever
method is used?
More posts by @Connie744
2 Comments
Sorted by latest first Latest Oldest Best
First create a PHP function that generates friendly URLs. Something like this would work, adjust to your liking.
function friendlyURL($id, $title) {
$string = $title;
$paramcount = func_num_args();
for ($i = 2; $i < $paramcount; $i++) {
$string .= "-" . func_get_arg($i);
}
$string = preg_replace('`&(amp;)?#?[a-z0-9]+;`i', '-', $string);
$string = htmlentities($string, ENT_COMPAT, "utf-8");
$string = preg_replace("`&([a-z]+);`i", "", $string);
$string = preg_replace("`['[]]`", "", $string);
$string = preg_replace(array("/[^A-Za-z0-9]/", "`[-]+`"), "-", $string);
$string = trim($string, '-');
return trim($id . "-" . $string, '-');
}
Next call the function in code replace your echo with this.
echo "<a href='/more/".friendlyURL($id, $title)."/'>$title</a>";
Next use a rewrite rule like.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^more/([0-9]+)[^/]*/?$ more.php?id= [QSA,L]
Usually you would have a structure similar to this:
website.com/products/1/this-is-my-product-title
where 1 is the ID of your product
htaccess rule would be:
^products/([0-9]+)/(.*)$ more.php?id=&title=
In order to make a clean url you should look up str_replace or regular expressions.
(For example replace all spaces with '-', remove all weird char etc)
In addition to this, you should make sure that the title part matches the real title of the ID, and make sure the file more.php is not accessed typing more.php in URL (look into super variable $_SERVER).
Terms of Use Create Support ticket Your support tickets Stock Market News! © vmapp.org2024 All Rights reserved.