3

I was wondering how can I create clean urls using PHP. Do I do this all in PHP or do I need to use mod_rewrite in some way? Can someone explain this to me in laymans terms?

Here is my current url a element link and how it looks in the browser

http://www.example.com/members/1/posts/page.php?aid=123

But I want it to read the pages title.

http://www.example.com/members/1/posts/title-of-current-page/
HELP
  • 14,237
  • 22
  • 66
  • 100

3 Answers3

2

First you need to generate "title-of-current-page" from PHP, using this function eg:

function google($string){
    $string = strtolower($string);
    $string = preg_replace('/[^a-zA-Z0-9]/i','-',$string);
    $string = preg_replace("/(-){2,}/",'$1',$string);
    return $string;
}

Second thing, you need to make a rewrite, but you should keep aid in form of "/123-title-of-current-page"

Rewrite would go something like this (I am ignoring your entire URL)

RewriteRule ^([0-9]+)-(.*?)$ page.php?aid=$1 [L,QSA]
Dejan Marjanović
  • 19,244
  • 7
  • 52
  • 66
  • if you have a db that matches your aid # to the title, you won't need to keep the number in the url string. just write a function that does a query lookup. much cleaner url that way. – TH1981 Dec 24 '10 at 01:01
  • 1
    Of course, problem occurs when there are two same names, also I think that WHERE id = 123 LIMIT 1 is much more faster, and reliable, what if he changes title, users from eg Google will get blank page, this way ID is always the same. Not that I don't use both ways. – Dejan Marjanović Dec 24 '10 at 01:10
1

You can do this using mod_rewrite:

You'll need to edit a file called .htaccess at the top level of your web folder. This is where you can specify certain settings to control the way Apache accesses items in this folder and below.

First things first. Let's turn on mod_rewrite: RewriteEngine On

RewriteRule ^([a-z]+)/([a-z\-]+)$ /$1/$2.php [L]

The rule matches any URL which is formed of lower case letters, followed by a /, then more lower case letters and/or hyphens, and appends .php to the end. It keeps track of anything wrapped in brackets () and refers to them later as $1 and $2, i.e. the first and second match. So if someone visits these URLs:

http://example.com/weblog/archive

it will be converted to following:

http://example.com/weblog/archive.php

You will find more details on :

http://wettone.com/code/clean-urls

rajmohan
  • 1,618
  • 1
  • 15
  • 36
0

You have to use a rewrite to direct all requests to an existing php file, otherwise you get all 404 not found errors because you are trying to get a page that simply is not there.

Unless you rewrite your 404 page to handle all requests and you definitely don´t want to go there...

jeroen
  • 91,079
  • 21
  • 114
  • 132