Set language in index.php

Asked

Viewed 357 times

4

I’m trying to develop a very simple system, contains 5 different languages, this part works perfectly, the problem is that when I first enter the site, in this case the file is the index.php, it shows the following error: inserir a descrição da imagem aqui

After choosing any language, it becomes normal, only happens when I enter for the first time. My question is: how do I define "Portuguese" as soon as the page has just been loaded, for example the url being http://localhost:8080/.../?lang=pt?
This is part of the code:

<select id="lang" name="lang" onchange="submitForm()">
                    <?php
                    switch ($_GET['lang']) {
                        case 'en':
                        $lng=1;
                        break;
                        case 'fr':
                        $lng=2;
                        break;
                        case 'sp':
                        $lng=3;
                        break;
                        case 'de':
                        $lng=4;
                        break;
                        default:
                        $lng=0;
                    }
                    $questao=array('Portugues','ingles','frances','espanhol','alemao');
                    ?>
                    <option value="pt"<?php if($_GET['lang'] != 'fr' && $_GET['lang'] != 'en' && $_GET['lang'] != 'sp' && $_GET['lang'] != 'de'){ echo " selected=\"selected\"";} ?>>Português</option>
                    <option value="en"<?php if ($_GET['lang'] == 'en'){ echo " selected=\"selected\"";} ?>>English</option>
                    <option value="fr"<?php if($_GET['lang'] == 'fr'){ echo " selected=\"selected\"";} ?>>Français</option>
                    <option value="sp"<?php if($_GET['lang'] == 'sp'){ echo " selected=\"selected\"";} ?>>Español</option>
                    <option value="de"<?php if($_GET['lang'] == 'de'){ echo " selected=\"selected\"";} ?>>Deutsch</option>
                </select>
            </td>
        </tr>
        <tr>
            <td colspan="3" class="pergunta" align="center">
                <hr>
                <?php echo $questao[$lng]; ?>
                <hr>
            </td>
        </tr>
        <tr>
  • 4

    As the parameter lang does not exist, the error occurs. Before the <select> add <?php $lang = isset($_GET["lang"]) ? $_GET["lang"] : false; ?> and replace the others $_GET["lang"] for $lang.

  • 2

    Very good Valdeir, thank you very much, it worked on perfection! It was simpler than I thought!

1 answer

0

If you are using PHP 7 you can use the coalescence operator:

 $lang = $_GET["lang"] ?? $_GET["lang"] : 'pt';

Browser other questions tagged

You are not signed in. Login or sign up in order to post.