mulekula
mulekula

Reputation: 29

2 languages ​​on the website using php

Help please organize bi-lingual website.

So first there are two files eng.php, es.php and they will be stored in translation site.

example:

$lang['hi'] = 'Hi';

How can I organize further language choice on the site and record information about the language in cookies?

Upvotes: 0

Views: 470

Answers (2)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

You can have two files like this.

Source of en.php:

$lang = array(
    'hi' => 'Hi'
);

Source of es.php:

$lang = array(
    'hi' => 'Hello'
);

And for the main content file, the source should be this way:

<?php
    session_start(); // Make sure you initialize cookies / session
    $allowedLangs = array('en', 'es'); // Array with allowed values
    if(isset($_SESSION['lang'])) { // If already user had stored language in session
        include $_SESSION['lang'] . ".php";
    } elseif(isset($_GET['lang']) && in_array($_GET['lang'], allowedLangs)) { // If user had requested like index.php?lang=en
        include $_GET['lang'] . ".php";
        $_SESSION['lang'] = $_GET['lang']; // Update the session with the language
    } else { // If user is visiting for the first time, then...
        include "en.php";
    }

    echo $lang['hi'];
?>

Upvotes: 2

Mohit Bumb
Mohit Bumb

Reputation: 2493

<?php
    if(!isset($_COOKIE['lang'])){
        ?>
        Choose Language...
        <a href="es.php">ES</a><a href="eng.php">ENG</a>
        <?php
    } else {
        if($_COOKIE['lang']=='es'){
            header("location:es.php");
        }
        elseif($_COOKIE['lang']=='eng'){
            header("location:eng.php");
        }
    }
?>

es.php // eng.php

<!--Your Content-->
<?php
    setcookie("lang","es/eng",time()+SECONDS_YOU_WANT)
?>

Upvotes: 0

Related Questions