【问题标题】:Friendly URL with ID to localized name带有 ID 到本地化名称的友好 URL
【发布时间】:2017-08-22 12:24:56
【问题描述】:

你能帮我做一个 htaccess 和 php 函数,它应该使 URL 看起来友好,比如 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

所以 URL /product.php?lang=en&category=01&product=05 应该变成 /product/coffee-and-tea/coffee05 和 DE /product/kaffee-und-tee/kaffee05

欢迎提出任何建议!

【问题讨论】:

  • 该代码对您有用吗?

标签: php mysql .htaccess


【解决方案1】:

前几天我正在处理这个问题。这是我最终使用的:

.htaccess

RewriteEngine on
RewriteBase /

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

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

这会将所有流量发送到 index.php,其中包含 $_SERVER['REQUEST_URI'] 的变量 url 为 $_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);

【讨论】:

  • url 函数由@Jorn btw 提供
猜你喜欢
  • 2017-10-23
  • 2012-06-05
  • 1970-01-01
  • 1970-01-01
  • 2018-04-14
  • 2017-01-29
  • 2012-04-08
  • 2018-04-11
  • 2014-02-26
相关资源
最近更新 更多