I work on a language switcher on a website in PHP. When I change the langauge with the switcher, the navigation menu’s language changes, but when I try to navigate to another page
on the nav menu, I get the following error message, and the ?lang= attribute does not appear at the end of the URL:
Fatal error: require_once(): Failed opening required ‘languages/.php’ (include_path=’.:/usr/share/php’) in /var/www/clients/client589/web1549/web/HERE_IS_MY_DOMAIN_NAME/config.php on line 20
Here is my PHP code in config.php:
session_start();
if (!isset($_SESSION['lang']))
$_SESSION['lang'] = $_GET['lang'];
else if (isset($_GET['lang']) && $_SESSION['lang'] != $_GET['lang'] && !empty($_GET['lang'])) {
if ($_GET['lang'] == "en")
$_SESSION['lang'] = "en";
else if ($_GET['lang'] == "fr")
$_SESSION['lang'] = "fr";
else if ($_GET['lang'] == "hu")
$_SESSION['lang'] = "hu";
}
require_once "languages/" . $_GET['lang'] . ".php";
I would be really grateful for some help! Thank you in advance.
2
Answers
This code seems to work, except that if I click on "Home" sub page in any language, it will return to the English 'Home' page:
Care needs to be taken when including files that are potentially set via a querystring parameter and consideration also of setting a default value initially if the user has made no choice regarding language. You could try something like this?
This has been tested using 3 local files in a sub-folder called languages. These 3 files are all identical to the following except the language name that is printed
On first invocation the default value (English) is used and becomes the session value. Clicking on any of the links will set that as the new session value and any attempt at setting an unknown value will yield no change.