1

我需要一种方法来包含基于 URL 中语言的 php 文件。现在这个脚本正在工作,但是当我有 10 或 20 种语言时,我想要一些更短的脚本,它仍然包含相同的信息。问题是,如果 URL 中的“lg”更改为不存在的语言,我想使用英语。

$langue=$_GET['lg'];
if ($langue == "da")
{ include"da.php";}
elseif ($langue == "de")
{ include"de.php";}
elseif ($langue == "en")
{ include"en.php";}
elseif ($langue == "es")
{ include"es.php";}
else { include"en.php";}

谁能缩短这个?

4

5 回答 5

5
if (empty($_GET['lg'])) {
  $lang = "en";
} else {
  $lang = $_GET['lg'];
}
if ( !preg_match('~^[a-z]{2}$~',$lang) ) {
  header('HTTP/1.1 403 Forbidden'); 
  exit;
}
$langfile = "$lang.php";
if (!is_readable($langfile)) {
  $lang     = "en";
  $langfile = 'en.php';
}
include $langfile;
于 2012-04-29T14:13:44.187 回答
1

只需使用:

$lang = (file_exists($_GET['lg'] . '.php')) ? $_GET['lg'] . '.php' : 'en.php';
include($lang);

编辑:根据评论,我应该指出,这段代码虽然实用且简洁,但确实很容易受到恶意攻击,基本上任何人都可以将 URL 变量设置为配置或其他敏感文件,然后对您的站点发起攻击,或窃取您的数据。因此,请确保$lang在调用 include 之前验证变量 - 也许使用一个简单的方法:

$allowed = array('en.php', 'fr.php');
if(in_array($lang, $allowed)){
    include($lang);
}
于 2012-04-29T14:12:20.580 回答
1
<?php
    $languages = array('da', 'de', 'en', 'es');

    $lang = 'en';
    if(!empty($_GET['lg']) && array_search($_GET['lg'], $languages) !== false) {
        $lang = $_GET['lg'];
    }
    include $lang.'.php';
?>
于 2012-04-29T14:14:04.233 回答
0

这样的事情呢?

if(isset($_REQUEST['lg']) && $_REQUEST['lg'] != '') $lg = $_REQUEST['lg'];

if(strstr($lg, '.')) die('Don\'t allow any . in the languages');

if(file_exists('path_to_language_files/'.$lg.'.php') {
    include('path_to_language_files/'.$lg.'.php');
} else {
    include('path_to_language_files/en.php');
}
于 2012-04-29T14:17:03.420 回答
0

I have a page which uses only two languages but i needed it to be open for adding more and so, i solved the same problem like this:

$allowed=array("da","de","en","es");
$default="de.php";
include(array_search($_GET["lg"],$allowed) === false ? $default : $allowed[array_search($_GET["lg"] , $allowed)].".php");

It should work similarly, except you can specify which files are allowed, and their names are taken from the array, so it should be safe from fake requests.

于 2012-04-29T15:46:59.540 回答