Change language on link click

2019-05-14 14:38发布

I have a links such as:

<a href="index.php?lang=en"><img src="images/uk.png" style="height:20px"/></a>

And and included page in index.php:

<?php
session_start();
header('Cache-control: private'); // IE 6 FIX

if(isSet($_GET['lang']))
{
$lang = $_GET['lang'];

// register the session and set the cookie
$_SESSION['lang'] = $lang;

setcookie("lang", $lang, time() + (3600 * 24 * 30));
}
else if(isSet($_SESSION['lang']))
{
$lang = $_SESSION['lang'];
}
else if(isSet($_COOKIE['lang']))
{
$lang = $_COOKIE['lang'];
}
else
{
$lang = 'en';
}

switch ($lang) {
  case 'en':
  $lang_file = 'lang.en.php';
  break;

  case 'gr':
  $lang_file = 'lang.gr.php';
  break;

  default:
  $lang_file = 'lang.en.php';

}

include_once 'languages/'.$lang_file;
?>

It changes the URL to index.php?lang=gr reads the parameter LANG and translates the page depends on this parameter.

How can I change my code to do it without passing the parameter to Url? What I mean is, that I want a user to stay on the same page and change the language on page refresh.

2条回答
Lonely孤独者°
2楼-- · 2019-05-14 15:17

There are a few ways to do this, one of which is to use a form and make the "submit" button your image. The form will use a POST method which will not include the variables in the URL. A get request will add ?lang=en

<div id="buttons">
    <form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>">
        <input type="hidden" name="lang" value="en">
        <button type="submit">
            <img src="images/uk.png" style="height:20px"/>
        </button>
    </form>
</div>

Change your code to use the $_POST variable:

if(isSet($_POST['lang']))
{
$lang = $_POST['lang'];
查看更多
够拽才男人
3楼-- · 2019-05-14 15:22

It would be as below ;

        <input type="submit" value="" class=<?php if( $_SESSION['lang']  == "tr" ) { echo "submittr";  } else { echo "submiten";} ?>>

In that case you will be changed type of the class

查看更多
登录 后发表回答