包含ID到本地化名称

时间:2017-08-22 12:24:57

标签: php mysql .htaccess

你能帮我制作一个htaccess和php函数,它应该像site.com/en/category/product那样制作友好的网址

该网站将使用多种语言,因此所有类别和产品名称都将进行本地化。

数据库将包含每种语言的记录 - product_id, category_id, name_en, category_en, name_de, category_de等。

因此数据库记录为:product_id - 05, category_id - 01, name_en - coffee05, category_en - coffee-and-tea, name_de - kaffee05, category_de - kaffee-und-tee

因此,网址/product.php?lang=en&category=01&product=05应该变为/product/coffee-and-tea/coffee05,而对于DE /product/kaffee-und-tee/kaffee05

欢迎任何建议!

1 个答案:

答案 0 :(得分:0)

前几天我正在研究这个问题。这就是我最终使用的内容:

的.htaccess

RewriteEngine on
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(.*)$ index.php?url=$1 [L,QSA]

这会将所有流量发送到index.php,其变量url包含$_SERVER['REQUEST_URI'] $_GET['url']

然后我使用了以下功能:

function url(){ 
if(isset($_GET['url'])){
            $routes = [];
            // get the URL from the base defined in the.htaccess file.
            // filter url
            # Example: www.yourdomain.com/example-page/hello/1/title/

            $url = filter_var(trim($_GET['url']),FILTER_SANITIZE_URL);
            // delete last / if it is there.
            $url = rtrim($url,'/');
            # Exampele change 1: $url = example-page/hello/1/title

            /*
             * Remove the - (dash) in the url : EX. example-page/hello. Classnames can't have the - (dash) so class is written as examplePage.
             * to call the function we need to remove the - (dash)
            */

            # Example change 2: $url = examplepage/hello/1/title
            $url = str_replace('-','', $url );
            // create array with all the url parts.
            # Example change 3: $url = ["examplepage","hello",1,"title"]
            $url = explode('/',$url);

            // add all array values to the var routes.
            foreach($url as $value){
                $routes[] = $value;
            }
        }
    return $routes;
}

此函数返回$_GET['url']的数组。从那里,在index.php上,您可以include基于数组中第一项的文件,以及为以下值分配值(或使用它们的索引)并决定如何处理来自那里的数据。

例如: 如果我的页面返回example.org/products/12, 我叫这个函数:

$url = url();
$page = $url[0];
$id = $url[1];
include($page);
echo productData($id);