如何创建一个简单的 PHP cookie 语言切换?

发布于 2024-12-10 10:45:19 字数 656 浏览 1 评论 0原文

我正在尝试设置一个简单的语言切换,我认为这是一个简单的语言切换。我以为我会使用 PHP cookie,但它们的行为并不符合预期。

我读过一些 cookie 教程,并在 StackOverflow 上查看了一些类似的示例,但我一定错过了一些东西,因为它无法让它正常工作。

我通过将语言作为 URL 变量(lang=en 或 lang=ru)传递来设置语言。这一切似乎都很好。然而,我目前设置 cookie 的代码似乎落后了一步,所以最初它没有任何值(我希望它默认为“en”),然后如果用户单击“ENG”按钮它仍然没有值,然后如果用户单击俄语,该值显示为“en”,然后如果我再次单击“ENG”按钮,该值显示为“ru”。

下面是我拼凑在一起的代码:

if( $_GET['lang'] ) {
    $lang = (string)$_GET['lang'];
    setcookie( 'lang', $lang, time() + 60*60*24*30 );
} elseif( !isset($_COOKIE['lang']) ) {
    $lang = 'en';
} else {
    $lang = $_COOKIE['lang'];
}

一旦我完成了这个工作,我打算使用 cookie 的值来使用一些条件 PHP 显示英语或俄语菜单。

谢谢。

I'm trying to set up, what I thought would be, a simple language switch. I thought I'd use PHP cookies, but they're not behaving as intended.

I've read a few cookie tutorials and looked at a few similar examples here on StackOverflow, but I must be missing something because it can't get it to work properly.

I'm setting the language by passing it as a URL variable (lang=en or lang=ru). That all seems to be fine. However, the code I have at the moment that sets the cookie seems to be one step behind, so initially it has no value (I'd like it to be 'en' by default), then if the user clicks the 'ENG' button it still has no value, and then if the user clicks Russian the value shows as 'en', and then if I click the 'ENG' button again the value shows as 'ru'.

Here's the code I've cobbled together:

if( $_GET['lang'] ) {
    $lang = (string)$_GET['lang'];
    setcookie( 'lang', $lang, time() + 60*60*24*30 );
} elseif( !isset($_COOKIE['lang']) ) {
    $lang = 'en';
} else {
    $lang = $_COOKIE['lang'];
}

Once I've got this working I intend to use the value of the cookie to display either the English or Russian menu using a bit of conditional PHP.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

岁月流歌 2024-12-17 10:45:19

感谢您的所有建议 - @Mob 让我朝着正确的方向前进,即在另一个页面上处理 cookie,然后将您发送回第一个页面。

我做了更多的思考和实验,终于解决了这个问题。我将发布下面的代码,以防其他人想使用它。

在您的主页上放置以下内容:

<form action="language_switcher.php" method="post">
    <select name="lang">
        <option value="en"<?php if( $_COOKIE["language"] == "en" ) { echo " selected"; } ?>>English</option>
        <option value="ru"<?php if( $_COOKIE["language"] == "ru" ) { echo " selected"; } ?>>Russian</option>
    </select>
    <input type="submit" value="Select Language">
</form>

<p>Language: <?php if( isset( $_COOKIE["language"] ) ) { echo $_COOKIE["language"]; } else { echo "<em>not set</em>"; } ?></p>

然后在另一个名为“language_switcher.php”的文件中放置以下代码:

$lang = "en";
if( isset( $_POST["lang"] ) ) {
    $lang = $_POST["lang"];
    setcookie ( 'language', $lang, time() + 60*60*24*30, '/', 'mydomain.com');
    header( "Location: /previous_page_url.php" );
}

用户选择一种语言并单击“选择语言”。然后,表单将表单值发送到“language_switcher.php”,后者设置 cookie,然后将用户发送回上一页。

完毕! :)

Thanks for all the suggestions - @Mob set me in the right direction, i.e. processing the cookie on another page and then sending you back to the first.

I did a bit more thinking and experimenting and I've finally solved it. I'll post the code below incase anyone else wants to use this.

On your main page put this:

<form action="language_switcher.php" method="post">
    <select name="lang">
        <option value="en"<?php if( $_COOKIE["language"] == "en" ) { echo " selected"; } ?>>English</option>
        <option value="ru"<?php if( $_COOKIE["language"] == "ru" ) { echo " selected"; } ?>>Russian</option>
    </select>
    <input type="submit" value="Select Language">
</form>

<p>Language: <?php if( isset( $_COOKIE["language"] ) ) { echo $_COOKIE["language"]; } else { echo "<em>not set</em>"; } ?></p>

Then in another file called 'language_switcher.php' put the following code:

$lang = "en";
if( isset( $_POST["lang"] ) ) {
    $lang = $_POST["lang"];
    setcookie ( 'language', $lang, time() + 60*60*24*30, '/', 'mydomain.com');
    header( "Location: /previous_page_url.php" );
}

The user chooses a language and clicks 'Select Language'. The form then sends the form value to 'language_switcher.php', which sets the cookie and then sends the user back to the previous page.

Done! :)

情深如许 2024-12-17 10:45:19

在重新加载设置页面或访问其他页面之前,无法访问 Cookie(换句话说,您无法在同一页面中设置和访问 Cookie)。

检查此代码:

if( $_GET['lang'] ) {
    $lang = (string)$_GET['lang'];
    setcookie( 'lang', $lang, time() + 60*60*24*30,'/' );
} elseif(  !$_GET['lang']) ) {
    $lang = 'en';
} else {
    $lang = $_GET['lang'];
}
header("Location: redirect_file.php")

然后在 redirect_file.php 中,您重定向回 cookie 页面。如果您想避免重定向循环,请执行一些检查。

A cookie is not accessible until the setting page has been reloaded or another page has been accessed (in other words, you cannot set and access a cookie in the same page).

Check this code out :

if( $_GET['lang'] ) {
    $lang = (string)$_GET['lang'];
    setcookie( 'lang', $lang, time() + 60*60*24*30,'/' );
} elseif(  !$_GET['lang']) ) {
    $lang = 'en';
} else {
    $lang = $_GET['lang'];
}
header("Location: redirect_file.php")

Then in redirect_file.php, you redirect back to the cookie page. Perform some checks if you want to avoid redirect loops.

静若繁花 2024-12-17 10:45:19
if ( !empty($_GET['language']) ) {
    $_COOKIE['language'] = $_GET['language'] === 'en' ? 'en' : 'nl';
} else if ( empty($_COOKIE['language']) ) {
    $_COOKIE['language'] = 'nl';
}
setcookie('language', $_COOKIE['language']);
if ( !empty($_GET['language']) ) {
    $_COOKIE['language'] = $_GET['language'] === 'en' ? 'en' : 'nl';
} else if ( empty($_COOKIE['language']) ) {
    $_COOKIE['language'] = 'nl';
}
setcookie('language', $_COOKIE['language']);
回首观望 2024-12-17 10:45:19

试试这个,

if ( !isset( $_GET['lang'] ) ) { 
    if ( isset( $_COOKIE['lang'] ) ) { 
        $lang = $_COOKIE['lang']; 
    } 
    else { 
        $lang = 'en'; 
    } 
} 
else { 
    $lang = (string)$_GET['lang']; 
    setcookie( 'lang', $lang, time() + 60*60*24*30 ); 
}

如果 GET 中没有设置 lang 指令,请检查是否设置了 cookie。

如果是,则使用其值,或者默认使用“en”。
如果设置了 lang 指令,则设置一个 cookie。

代码几乎相同,但进行了一些优化。
(最好将出现次数最多的条件放在 if 之上。

Try this one,

if ( !isset( $_GET['lang'] ) ) { 
    if ( isset( $_COOKIE['lang'] ) ) { 
        $lang = $_COOKIE['lang']; 
    } 
    else { 
        $lang = 'en'; 
    } 
} 
else { 
    $lang = (string)$_GET['lang']; 
    setcookie( 'lang', $lang, time() + 60*60*24*30 ); 
}

If the lang directive is not set in GET, check if there is a cookie set.

If it is use its value, or use 'en' by default.
If the lang directive is set, set a cookie.

It's pretty much the same code, but a bit optimized.
(It's better to put conditions that appear the most on top of ifs.

孤檠 2024-12-17 10:45:19

我使用 PHP 的 $_SERVER['PHP_SELF'] 刷新当前页面并考虑所选的语言。

附上示例代码。文件名:语言切换器.php

<?php

    error_reporting(E_ERROR);

    $lang = "en";

    if( isset( $_COOKIE["language"] ) ) { 
       $lang = $_COOKIE["language"]; 
    }

    if( isset( $_POST["lang"] ) ) {
       $lang = $_POST["lang"];
       setcookie ( 'language', $lang, time() + 60*60*24*30, '/','localhost');
       $refresh = $_SERVER['PHP_SELF'];
       header( "Location: $refresh");
    }
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Test Page Language Toggle</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>

<body>

    <?php 
      // Text definitions
      $text = array(
      'en' => array(
            'selectlang' => 'Select Language',
            'lingua' => 'Language: ',
            'filename' => 'You are in this location: '
          ),
      'fr' => array(
            'selectlang' => 'Séléctionner',
            'lingua' => 'Langue: ',
            'filename' => 'Vous lisez ce fichier: '
          )
      );

    ?>

    <form action="language_switcher.php" method="post">
        <select name="lang">
            <option value="en"<?php if( $_COOKIE["language"] == "en" ) { echo "selected"; } ?>>English</option>
            <option value="fr"<?php if( $_COOKIE["language"] == "fr" ) { echo " selected"; } ?>>Français</option>
        </select>
        <input type="submit" value="<?php echo $text[$lang][selectlang]; ?>">
    </form>

    <p><?php echo $text[$lang][lingua]; if( isset( $_COOKIE["language"] ) ) { echo $_COOKIE["language"]; } else { echo "<em>not set</em>"; } ?></p>

    <br>
    <p><?php echo $text[$lang][filename] . $_SERVER['PHP_SELF']; ?></p>

</body>
</html>

I used PHP's $_SERVER['PHP_SELF'] to refresh current page and take into account the language selected.

Sample code enclosed. file name : language_switcher.php

<?php

    error_reporting(E_ERROR);

    $lang = "en";

    if( isset( $_COOKIE["language"] ) ) { 
       $lang = $_COOKIE["language"]; 
    }

    if( isset( $_POST["lang"] ) ) {
       $lang = $_POST["lang"];
       setcookie ( 'language', $lang, time() + 60*60*24*30, '/','localhost');
       $refresh = $_SERVER['PHP_SELF'];
       header( "Location: $refresh");
    }
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Test Page Language Toggle</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>

<body>

    <?php 
      // Text definitions
      $text = array(
      'en' => array(
            'selectlang' => 'Select Language',
            'lingua' => 'Language: ',
            'filename' => 'You are in this location: '
          ),
      'fr' => array(
            'selectlang' => 'Séléctionner',
            'lingua' => 'Langue: ',
            'filename' => 'Vous lisez ce fichier: '
          )
      );

    ?>

    <form action="language_switcher.php" method="post">
        <select name="lang">
            <option value="en"<?php if( $_COOKIE["language"] == "en" ) { echo "selected"; } ?>>English</option>
            <option value="fr"<?php if( $_COOKIE["language"] == "fr" ) { echo " selected"; } ?>>Français</option>
        </select>
        <input type="submit" value="<?php echo $text[$lang][selectlang]; ?>">
    </form>

    <p><?php echo $text[$lang][lingua]; if( isset( $_COOKIE["language"] ) ) { echo $_COOKIE["language"]; } else { echo "<em>not set</em>"; } ?></p>

    <br>
    <p><?php echo $text[$lang][filename] . $_SERVER['PHP_SELF']; ?></p>

</body>
</html>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文