I have problems with php multilanguage. I'm using function *check_lang* and it works fine in one page, but once I go to another page the $_SESSION['lang'] variable $lang turns back into default (en). What is the problem?
<?php
function check_lang() {
if(isset($_GET['lang'])
{
$lang = $_GET['lang'];
$_SESSION['lang'] = $lang
}
if (!isset($_SESSION['lang'])) {
$lang = 'en';
} else {
$_SESSION['lang']=$lang;
}
//directory name
$dir = 'languages';
return "$dir/$lang.lng";
}
?>
You have to:
session_start();
At the top of each of your scripts in which you want to use session variables.
You need to call session_start() on each page you're planning on using the $_SESSION[] global in. That's what tells PHP that it should look up the session_id from the user's cookies or the query string so that PHP knows which session's values to use.
Reference.
Related
The session I set is lost after the form is submitted.
I had built the session class to set new session, unset and so on. In function.php of wordpress template.
function.php
if (!session_id()) {
session_start();
}
include get_template_directory() . "/custom/session.php";
Session.php
class session {
function __construct() {
}
function set_flashdata($name, $value) {
$_SESSION[$name] = $value;
}
function flashdata($name) {
if (isset($_SESSION[$name])) {
$str = $_SESSION[$name];
return $str;
} else {
return FALSE;
}
}
function userdata($name) {
if (isset($_SESSION[$name])) {
return $_SESSION[$name];
} else {
return FALSE;
}
}
function set_userdata($name, $value) {
$_SESSION[$name] = $value;
}
function unset_userdata($name) {
if (isset($_SESSION[$name])) {
unset($_SESSION[$name]);
}
}
}
I try to set session as :
<?php
$sess = new session();
$sess->set_userdata('sess_name',"some value");
?>
<form action="get_permalink(212);">
//input buttons
</form>
After submit the form it goes to the permalink(212). Then I tried.
<?php
$sess = new session();
$value = $sess->userdata('sess_name');
var_dump($value); //returns false. That means session is lost after form submit. Why?
?>
You need to move session start/resume into your Session's constructor.
Like so:
class session
{
function __construct()
{
if (! session_id()) {
session_start();
}
}
Another thing to mention, every time you'll do new Session you'll be getting an object of the same functionality working with same global variable $_SESSION.
You don't need more than one $session object, it would be a good time to look into Singleton pattern.
You have to call always session_start() for each request.
The mission of session_start() is:
Creates a new session
Restart an existing session
That means, if you have created a session, and you don't call to the method session_start(), the variable $_SESSION is not going to be fulfilled.
Except: If in your php.ini you have set the option session.auto_start to 1, then, in that case it is not needed to call the session_start() because the variable $_SESSION is fulfilled implicitly.
You need to use wordpress global variable for condition that session is set or not something like :
global $session;
if (!session_id()) {
session_start();
}
include get_template_directory() . "/custom/session.php";
It might be due to www. at the start of your website domain. Make sure that both of pages use the same structure.
Also I faced with the same issue long time ago when the form sends the data to a secured address (https://)
I hope these two items may help you.
Sounds to me like session_start() is not set at the start of the page that get_permalink(212;) refers to.
I have almost no experience with WP itself though, so I might misunderstand the functionality of get_permalink()
I agree with the answer from #rock3t to initialize session in constructor of class, but every time a class object is initiated, it will go to check for session!
Instead, if you are fine, the simplest way to get access to session is by adding following lines to your wp-config.php file before the call to wp-settings
if (!session_id())
session_start();
This will set/initialize session globally and you won't need to set/check for session_start in constructor of a class.
Thank you.
I am using jquery throughout a php project, so all pages load dynamically into the main page, I am trying to make links only visible to a certain user, so if they goto the main page and append the URL, i.e ?mode=55rt67 this gets stored as a variable and can be checked throughout the app. I am using the below, but it doesnt work. any suggestions?
if (empty($_GET)) {
$mode = "user";
}else{
define ('$mode', '($_GET['mode']);
}
define is used to declare constants, you want to use a variable, not a constant.
UPDATED (use session to store mode variable):
if (empty($_GET)) {
$_SESSION['mode'] = "user";
}else{
$_SESSION['mode'] = $_GET['mode'];
}
And don't forget to use session_start on every page
Change your code with below code.
// Try this
if(isset($_GET['mode']) ){
define ('mode',$_GET['mode']);
}else{
define ('mode',"user");
}
echo mode;
//OR
if(isset($_GET['mode']) ){
global $mode = $_GET['mode'];
}else{
global $mode = "user";
}
echo $mode;
if (empty($_GET)) {
$_SESSION['mode'] = "user";
}else{
$_SESSION['mode'] = $_GET['mode'];
}
The above solution worked perfectly, added session_start to the index page, and it now carries through the rest of the pages.
Awesome, thanks all
I use $_SESSION array to save the language of my website and It works fine but I found lately some problem when I log out of my website I use this code :
<?php
if (isset($_SESSION['logged_in']))
{
session_destroy();
header('Location: ./index.php');
}
?>
So when I logout the $_SESSION['lang'] variable is destroyed and the website language go back to default so I did this :
<?php
if (isset($_SESSION['logged_in']))
{
$lang = $_SESSION['lang'];
session_destroy();
$_SESSION['lang'] = $lang;//if I echo this $_SESSION['lang'] I get the website language but after header('Location: ./index.php'); it still deleting the lang variable
header('Location: ./index.php');
}
?>
Is there something I could do it here to keep the value ???
Save this value in cookies(if it doesn't contains sensible information).
I am working on a website. I would like the website to redirect from index.php to index.php?lang=En.
This is because the site is multi-lingual and the default language needs to be set to English on the home page. I used the header() method to do this but that causes a redirect loop as the site keeps reloading forever.
How can I overcome this barrier?
In your PHP:
<?php
// Default to English if $_GET['lang'] isn't set
$lang = isset($_GET['lang']) ? $_GET['lang'] : 'En';
// If language not in array of available languages, reset to English
if (!in_array($lang, array('En', 'Es', 'Fr'))) {
$lang = 'En';
}
header('Location: index.php?lang=' . $lang);
?>
In your HTML:
English,
Español,
Français
I would do like this:
if(!isset($_GET['lang']) {
header('location: http://www.example.com/index.php?lang=En');
}
Check if the lang parameter exists in the URL, and do the redirect only if it doesn't:
if (!isset($_GET['lang']) {
header('Location: http://www.example.com/index.php?lang=En');
}
Hey all,
I am trying to internationalise my website with php. I am very new to PHP!
The index.php starts with this:
<?php session_start(); ?>
<?php include 'api/locale.php'; ?>
<html>
<!-- ... -->
<div><?php loc('foo') ?></div>
The locale.php looks like this:
<?php
if(isset($_GET['lang']) {
$_SESSION['lang'] = $_GET['lang'];
} else {
$_SESSION['lang'] = 'en'; // default value
}
// use the necessary language file
include('/locale/' . $_SESSION['lang'] . '.php');
// get phrase from URL
if (isset($_GET["phrase"]))
loc($_GET["phrase"];);
function loc($phrase)
{
global $lang;
if(array_key_exists($phrase, $lang)) {
echo $lang[$phrase];
} else {
echo $phrase;
}
}
?>
The idea is I want to use the function loc($phrase) to get the content either in German or English. But here is the problem:
If I have the code like this, I always get the english version, because in locale.php I can not get the lang from the URL: $_GET['lang'] is undefined. Therefore, the session language is always set to the default language (en).
However, if I move the session_start(); into the file locale.php, the internationalisation works:
index.php:
<?php include 'api/locale.php'; ?>
<html>
<!-- ... -->
<div><?php loc('foo') ?></div>
locale.php:
<?php
session_start();
if(isset($_GET['lang']) {
$_SESSION['lang'] = $_GET['lang'];
// ... rest the same as above
Why is it like this? Am I doing something conceptually wrong? The problem is I am also using this locale.php in ajax calls to get international content for dynamically generated HTML elements:
function loc(phrase)
{
var locString;
$.ajax({
// force synchronous ajax call, to return with locString
async: false,
// url with to be translated id
url: "api/locale.php?phrase=" + phrase,
// "get" for small data (otherwise post)
method: "get",
// callback function after server has reveiced information
success: function (data)
{
locString = data;
}
});
return locString;
}
So if I call locale.php over and over again with this AJAX call, aren't there new sessions starting over and over again? I am not sure if I designed my functions correctly. I am happy about any comments!
Thank you!
=============== EDIT ===============
ok, I tried a new way now:
session.php
// session starts at this point
session_start();
// internationalisation in EN and DE
$allowedLangs = array('en', 'de');
// check lang-parameter given in URL and set language from there
if(isset($_GET['lang']) && in_array($_GET['lang'], $allowedLangs))
$_SESSION['lang'] = $_GET['lang'];
if(!isset($_SESSION['lang']))
$_SESSION['lang'] = 'en'; // default value
locale.php
// include correct languguage file
$root = realpath($_SERVER["DOCUMENT_ROOT"]) ;
include($root . '/locale/' . $_SESSION['lang'] . '.php');
// get phrase from URL and translate it
if (isset($_GET["phrase"]))
{
$phrase = $_GET["phrase"];
global $lang;
if (array_key_exists($phrase, $lang))
echo $lang[$phrase];
else
echo $phrase;
}
both files get included in index.php
<?php include 'api/session.php'; ?>
<?php include 'api/locale.php'; ?>
However, if I locale a phrase with ajax now, the following error message appears:
Notice: Undefined variable: _SESSION in ... /locale.php on line 4
How can that be? I thought $_SESSION is superglobal ?!?
When you call the version of api/locale.php with the session_start via ajax, not a new but the same session will start, which is the correct behaviour.
Word start maybe confusing you but the session start will supply the information of the current session correctly, not a new one. So nothing to worry about.
Also you may consider looking at
$_SERVER['HTTP_ACCEPT_LANGUAGE']
before starting to ajax ping-pong of the server and client for an initial language quick guess...
For the two versions of your code, it is not a mystery why it works when session_start is
in locale.php.
The cause is:
Your ajax call is not entering your script from index.php, it enters directly to api/locale.php.
If you do not session_start in api/locale.php, the ajax call will enter into a sessionless php invocation.
So it will keep the default value since session data is neither can be fetched or can be recorded.
I think there is something conceptually wrong in your locale.php file.
The fact that you always set $_SESSION['lang'] is a bad smell.
There should be a case when you dont set the value of $_SESSION['lang']and just use the value of$_SESSION['lang']without modifying it.
With your locale file as it is , and your ajax call that does not pass 'lang' as a parameter, you will always get the default language.
But anyway your local.php file should start with session_start(); as explained by ishan.
By the way you should not use 'echo' inside your function loc. Instead return the result and do
echo loc('foo');
It would do the same job, but your loc function would be more reusable.
Hi Marcus I will try to answer your question in the comments.
$_SESSION id indeed a super global. But you need to call session_start() for it to works.
That's why it does not work anymore in locale.php
The problem is that your locale.php file is serving two purposes at the same time.
It should just translate but not be reachable directly from an url.
So you should do something like this :
session.php
`
//here you define a default value. So whatever happens, you know that $_session['lang']
//will always be set.
if(! isset ($_SESSION['lang'] {
$_SESSION['lang'] = 'en'; // default value
}
// internationalisation in EN and DE
$allowedLangs = array('en', 'de');
// check lang-parameter given in URL and set language from there
//if necessary, the default value will be overwritten.
if(isset($_GET['lang']) && in_array($_GET['lang'], $allowedLangs)) {
$_SESSION['lang'] = $_GET['lang'];
}
`translate.php
function getTranslation ($phrase, $lang='en') {
$root = realpath($_SERVER["DOCUMENT_ROOT"]) ;
include($root . '/locale/' . $lang . '.php');
//the array with the phrases and their translations should not be called $lang
//to avoid confusion. Let's call it $translations
if (array_key_exists($phrase, $translations))
return $translations[$phrase];
else
return $phrase;
}
}
locale.php
`
This file is to be called in ajax.
It will works providing $_SESSION['lang'] as already been defined
(in index.php for example). Otherwise you fall back to the default lang.
include 'path_to_translate/translate.php';
session_start();
if(isset($_SESSION['lang'] {
$lang = $_SESSION['lang'];
} else {
$lang = 'en';
}
$phrase = $_GET['phrase'];
echo getTranslation($phrase, $lang);
index.php
session_start();
include 'api/session.php';
include 'path_to_translate/translate.php';
$lang = $_SESSION['lang'];
<some html>
//to translate anything
<?php echo getTranslation($anything, $lang) ?>
</some html>
Hope this will help. Off course I can not test all this code , so their might be some mistake. But that's the general idea.
I tried not to change to much what you' have done. But there is still a problem. You should not define the lang in index.php. If there is a form in your index to choose the lang. Make a call in ajax to set_lang.php. It is not for the index to set the lang in session.