I want to write friendly urls by changing fullnews.php?id=123 to something like

fullnews.php/123/This-is-the-Headline or fullnews.php/This-is-the-Headline-123

"This is the Headline" is the headline of the news item as selected from the database,
id is the id selected from the database, I want to attach the id to the headline in url
so as to make it unique in case of similar headlines.

The db query code is something like this:

$sel=mysql_query("select id, headline from newstable");
echo "<a href='fullnews.php?id=$id'>$headline</a>";

What htacess code should I use and how do I re-write the hyperlink "<a href='fullnews.php?id=$id'>$headline</a>"
to achieve the goal.


Recommended Answers

All 3 Replies

Change echo "<a href='fullnews.php?id=$id'>$headline</a>"; to echo '<a href="fullnews.php/' . $headline . '-' . $id . '">' . $headine . '</a>';

In htaccess

RewriteEngine On
RewriteRule ^fullnews.php/(.*)-[0-9] fullnews.php?id=$2

It'll rewrite to "fullnews.php?id=123" when visitor visits fullnews.php/headine-123", headline is that you set from query.

Thanks. I don't seem to get it yet, I tried the above, it redirects to fullnews.php/index.php, which doesn't exist

1) First of all make sure all your href should have seo url, which you finally want
i.e. fullnews.php/123/This-is-the-Headline
So below code will make such href.

function seo($input){
    $input = mb_convert_case($input, MB_CASE_LOWER, "UTF-8"); //convert UTF-8 string to lowercase
    $a = array('č','ć','ž','đ','š');
    $b = array('c','c','z','dj','s');
    //$input = strtr($input, "čćžđšè", "cczdse"); not working properly :(
    $input = preg_replace("/[^a-zA-Z0-9]+/", "-", $input); //replace all non alphanumeric chars with dashes
    $input = preg_replace("/(-){2,}/", "$1", $input); //prevent repeating dashes
    $input = trim($input, "-"); //trim dashes both sides, if any
    return $input;
echo "<a href='fullnews.php/".$id."/".seo($headline)."'>$headline</a>";

2) Add below code in htaccess file.

RewriteEngine On
RewriteRule ^fullnews\.php/([^/]*)/([^/]*)$ /fullnews.php?id=$1&headline=$2 [L]

So that
The original URL:
The rewritten URL:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.