Change language on link click

2019-05-14 15:04发布

问题:

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.

回答1:

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'];


回答2:

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