0

So I am with a little issue. Everything in this code is working but when someone put the link like this ?lang=enASa instead of ?lang=en for some reason it just shows the "define" (Don't know if I can call that a define) Example: Instead of showing: Title it shows this: _TITLE . The code is this:

<?php
    session_start();

    // Set Language variable
    if(isset($_GET['lang']) && !empty($_GET['lang'])){
        $_SESSION['lang'] = $_GET['lang'];

        if(isset($_SESSION['lang']) && $_SESSION['lang'] != $_GET['lang']){
            echo "<script type='text/javascript'> location.reload(); </script>";
        }
    }

    // Include Language file
    if(isset($_SESSION['lang'])){
        include "lang_".$_SESSION['lang'].".php";
    }else{
        include "lang_en.php";
    }
?>

In the pages I am using this (<?= _TITLE ?>) to replace the words:

<h3 style="color: white" class="subheading left"><?= _TITLE ?></h3>

And to translate i am using this file (lang_en.php):

<?php

define("_TITLE", "Title");

All code works fine, and I was hoping that someone could help me here forcing to use default English when the lang is not valid. Example: If anyone tries www.example.com/index.php?lang=edadsa instead of www.example.com/index.php?lang=en our just www.example.com/index.php force to use the default.

yyppooi
  • 19
  • 3
  • Don't you get a warning saying that it can't include the file `lang_enASa.php` or don't you have error_reporting and display errors turned on? – Magnus Eriksson May 30 '18 at 14:24
  • @Magnus Eriksson No –  May 30 '18 at 14:26
  • Then I would recommend that you read this post: [How do I get PHP errors to display?](http://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display). That's pretty crucial when it comes to debugging. What actually happened was that the constant `_TITLE` wasn't defined (since it couldn't load the file that defines it), so PHP assumed that you meant to use `'_TITLE'` (a string) and echoed that for you. – Magnus Eriksson May 30 '18 at 14:27
  • Your code is awfully insecure – user70960 May 30 '18 at 14:30
  • @user70960 how can I make it more secure? –  May 30 '18 at 14:34
  • @Peter You should not access GET directly, use [filter_input](http://php.net/manual/en/function.filter-input.php) instead to sanitize the string and then verify, if that language is allowed (language file exists or is in the language list somewhere) for example. – Tomáš Vališka May 30 '18 at 14:44
  • Could you tell what I need exactly to replace? I don't want to do the wrong things –  May 30 '18 at 14:50

1 Answers1

3

You have to check if a language file exists for the given language, before calling the include.

// Include Language file
if(isset($_SESSION['lang']) && file_exists("lang_".$_SESSION['lang'].".php")){
 include "lang_".$_SESSION['lang'].".php";
}else{
 include "lang_en.php";
}