如果$ _GET == $ lang多语言页面更改

时间:2016-01-29 11:07:59

标签: php html

此选择表单在单击时加载正确的域,页面和语言变量。但是当用户连续两次更改语言时,url有两个语言变量。例: domain.com/page.php?lang=en_us?lang=nl_be

如何防止这种情况?

<div class="country_selector"><?php echo $lang['REGION']; ?>
        <select id="source" onchange="navigateTo(this, 'window', false);">
            <option value="https://domain.cc<?php echo $_SERVER['REQUEST_URI']; ?>?lang=en_eu">Europa</option>
            <option value="https://domain.be<?php echo $_SERVER['REQUEST_URI']; ?>?lang=nl_be">België</option>
            <option  value="https://domain.nl<?php echo $_SERVER['REQUEST_URI']; ?>?lang=nl_nl">Nederland</option>
            <option  value="https://domain.uk<?php echo $_SERVER['REQUEST_URI']; ?>?lang=en_uk">United Kingdom</option>
            <option  value="https://domain.cc<?php echo $_SERVER['REQUEST_URI']; ?>?lang=en_us">United States</option>
        </select>
    </div>

1 个答案:

答案 0 :(得分:2)

$_SERVER['PHP_SELF']包含查询字符串。请改用$_SERVER['REQUEST_URI']

如果您希望在生成的网址中保留$_GET[]中的更多参数,则另一个选项是编写一个分析$_SERVER['QUERY_STRING']lang的函数,添加或替换{ {1}}参数并生成网址:

function generateLanguageURL(array $params, $lang)
{
    // Add the language to $params (or replace it if it's already there)
    $params['lang'] = $lang;

    // Generate the query string, append it to the script's URI and return
    // Generate partial URLs. There is no need to put the protocol
    // and the host name in the URL if they are the same as of the current page.
    return $_SERVER['PHP_SELF'].'?'.http_build_query($params);
}

第一个参数(array $params)允许您使用$_GET生成包含当前查询字符串array()的所有参数的URL,以生成没有其他参数的URL或任何其他组合您需要的参数(例如array('q' => 'foo', 'items' => 10, 'page' => 2))。

如何使用它:

<div class="country_selector"><?php echo $lang['REGION']; ?>
    <select id="source" onchange="navigateTo(this, 'window', false);">
        <option value="<?php echo generateLanguageUrl($_GET, 'en_eu'); ?>">Europa</option>
        <option value="<?php echo generateLanguageUrl($_GET, 'nl_be'); ?>">België</option>
        <option value="<?php echo generateLanguageUrl($_GET, 'nl_nl'); ?>">Nederland</option>
        <option value="<?php echo generateLanguageUrl($_GET, 'en_uk'); ?>">United Kingdom</option>
        <option value="<?php echo generateLanguageUrl($_GET, 'en_us'); ?>">United States</option>
    </select>
</div>

您可以使用当前页面的值作为默认值,通过添加脚本路径,主机名和协议作为可选参数来改进功能,让它生成站点所需的任何URL。