0

现在,我有一个使用两种语言(法语和英语)的网站。

它目前的工作方式是,如果有人去mysite.com/folder/file.php,例如,file.php它只是一个脚本,它确定要使用哪种语言,获取它自己的路径和文件名(file.php)并提供服务mysite.com/en/folder/file.php(如果语言是英语)。但是,URL 中显示的仍然是mysite.com/folder/file.php.

对于任何文件夹和任何文件,都使用相同的脚本。如果我想添加一个新文件,我必须将文件添加到用户在浏览器中键入的文件夹以及enandfr文件夹中。

我可以做一些.htaccess技巧,以便输入任何 URL,.php打开一个文件,检查语言和请求的文件夹/文件,然后提供正确的语言文件?

这是为 URL 中的任何文件提供的 php 文件。

<?php 

// Get current document path which is mirrored in the language folders
$docpath = $_SERVER['PHP_SELF'];

// Get current document name (Used when switching languages so that the same
current page is shown when language is changed)
$docname = GetDocName();

//call up lang.php which handles display of appropriate language webpage.
//lang.php uses $docpath and $docname to give out the proper $langfile.
//$docpath/$docname is mirrored in the /lang/en and /lang/fr folders
$langfile = GetDocRoot()."/lang/lang.php";
include("$langfile"); //Call up the proper language file to display

function GetDocRoot()
{
 $temp = getenv("SCRIPT_NAME");
 $localpath=realpath(basename(getenv("SCRIPT_NAME")));
 $localpath=str_replace("\\","/",$localpath);
 $docroot=substr($localpath,0, strpos($localpath,$temp));
 return $docroot;
}

function GetDocName()
{
$currentFile = $_SERVER["SCRIPT_NAME"];
$parts = Explode('/', $currentFile);
$dn = $parts[count($parts) - 1];
return $dn;
}

?>
4

1 回答 1

1

一个常见的解决方案是让站点的根目录 (/index.php) 找出首选语言,然后重定向到包含语言代码的 URL。如果您的文件随后按磁盘上的语言分隔,则可以直接请求它们。

或者您可以在 .htaccess 或您的主机设置中添加一个简单的正则表达式,以从请求的 URL 中获取语言并将所有类似的请求发送到一个文件:

RewriteEngine On
RewriteRule ^/(.+)/folder/file.php$ /folder/file.php?lang=$1

然后$_GET['lang']在 PHP 中引用以查看请求的语言。您可能希望将其扩展为更普遍地适用于站点上的所有类似文件,例如:

RewriteRule ^/(.+?)/(.+)\.php$ /$2.php?lang=$1
于 2012-09-09T22:10:00.867 回答