我可以将mod_rewrite与switch case一起使用

时间:2017-08-22 08:55:14

标签: php .htaccess mod-rewrite

我的网站有2种语言。当我更改语言时,我希望URL也会更改,类似于:

www.domain.com

改为:

www.domain.com/th

和此:

www.domain.com/en

我的php:

的config.php

<?php
session_start();
error_reporting(E_ALL ^ E_NOTICE);
ini_set('display_errors', 1);

if(empty($_SESSION['language'])){
    $_SESSION['language'] = "th";
}

if ($_SESSION['language'] == "th") {
    include $_SERVER['DOCUMENT_ROOT'] . "/language/th.php";
} else {
    include $_SERVER['DOCUMENT_ROOT'] . "/language/en.php";
}

$base_url = "/";

function lang($th, $en) {
    if ($_SESSION['language'] == "th") {
        return $th;
    } else {
        return $en;
    }
}

lang.php

<?php

session_start();

switch ($_POST["lang"]) {
    case "th":
        $_SESSION['language'] = "th";
        echo json_encode("complete");
        break;

    case "en":
        $_SESSION['language'] = "en";

        echo json_encode("complete");
        break;

    default :
        break;
}
?>

指向更改语言的链接

<li><a href="javascript:lang('th');" <?= $_SESSION['language'] == "th" ? 'class="active"' : ''; ?> >TH</a></li>
<li><a href="javascript:lang('en');" <?= $_SESSION['language'] == "en" ? 'class="active"' : ''; ?> >EN</a></li>

我可以使用.htaccess执行此操作吗?

1 个答案:

答案 0 :(得分:0)

不,您无法从.htaccess加入PHP会话。但您可以使用mod_rewrite重写config.php的每个请求。

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    # Only for non-existing directories, files or symlinks
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteRule .* config.php [L]
</IfModule>