David
David

Reputation: 93

include_once gives an error when variable isn't passed in the url

index.php

<?php include_once 'lang.php'; ?>

lang.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 'pl':
        $lang_file = 'lang.pl.php';
        break;
}
include_once 'languages/' . $lang_file;
?>

In lang.en.php and lang.pl.php I have arrays with content.

When website is opened for the first time I get two warnings:

Warning: include_once(languages/) [function.include-once]: failed to open stream: No such file or directory in blah/blah/blah/lang.php on line 37

Warning: include_once() [function.include]: Failed opening 'languages/' for inclusion (include_path='.:/usr/local/lib/php-5.2.17/lib/php') in blah/blah/blah/lang.php on line 37

Then when I select a language on the webpage, and variable "lang" is passed in the url (e.g. index.php?lang=en) everything works ok. How to fix it?

Upvotes: 0

Views: 534

Answers (2)

Dyin
Dyin

Reputation: 5376

Maybe just add a default section for the switch:

switch($lang){
  case 'en':
    $lang_file='lang.en.php';
    break;
  case 'pl':
    $lang_file='lang.pl.php';
    break;
  default:
    // This will set a default language file.
    $lang_file='lang.en.php';
}
include_once 'languages/'.$lang_file;

This time, when $lang is not set to 'en' or 'pl', the switch will return setting the $lang_file to lang.en.php. If you want pl to be set by default, however, you can change that.

Upvotes: 0

jeremyharris
jeremyharris

Reputation: 7882

If you don't define a language, it tries to load 'languages/' (a directory). You should have a default in your switch statement. If you want the default language to be 'en', for example:

switch ($lang) {
  case 'pl':
  $lang_file = 'lang.pl.php';
  break;
  default: // en will fall here, too
  $lang_file = 'lang.en.php';
  break;
}

Otherwise $lang_file is undefined and will of course fail to load.

Upvotes: 1

Related Questions