PHP - How to add a pages title to the URL? And how to create a clean url using PHP

后端 未结 3 580
刺人心
刺人心 2021-01-15 09:39

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?<

相关标签:
3条回答
  • 2021-01-15 09:54

    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...

    0 讨论(0)
  • 2021-01-15 10:02

    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

    0 讨论(0)
  • 2021-01-15 10:07

    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]
    
    0 讨论(0)
提交回复
热议问题