PHP cookies issue, not including language file - php

I have a piece of code that should redirect user if there's no cookies in the session..
if (isset($_GET['lang'])) {
if (in_array($_GET['lang'], $jezici)) {
$lang = $_GET['lang'];
// register the session and set the cookie
$_SESSION['lang'] = $lang;
setcookie("lang", $lang, time() + (3600 * 24 * 30));
} else {
$lang = 'hr';
$_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 if (empty($_GET['lang']) || !isset($_GET['lang'])) {
$trenutni_file = basename($_SERVER['PHP_SELF']);
?>
<META http-equiv="refresh" content="0;URL=http://<?php echo $domena; ?>/<?php echo $trenutni_file; ?>?lang=hr">
<?php
exit();
}
?>
This is how I include it in index.php
$langArray = include 'lang/'.$lang.'.php';
But sometimes I get this error failed to include lang/.php ... This code is obviously not doing everything right.. If no cookie is set in the session I would redirect user to index.php?lang=hr... Any help?

Your last condition (empty($_GET['lang']) || !isset($_GET['lang'])) is redundant itself, since empty already checks if the function is set, as you can read here. Also, it is redundant with the first condition.
Moreover, you are lacking a condition to determine if in the case the var is set in session or cookie, it actually is not empty (it could be set as an empty string, for example)
I would change all your isset calls for an empty call, and add a final, standalone condition, to chek if $lang is set, no matter how, and if it has a valid value
if (!empty($_GET['lang'])) {
if (in_array($_GET['lang'], $jezici)) {
$lang = $_GET['lang'];
// register the session and set the cookie
$_SESSION['lang'] = $lang;
setcookie("lang", $lang, time() + (3600 * 24 * 30));
} else {
$lang = 'hr';
$_SESSION['lang'] = $lang;
setcookie("lang", $lang, time() + (3600 * 24 * 30));
}
} else if (!empty($_SESSION['lang'])) {
$lang = $_SESSION['lang'];
} else if (!empty($_COOKIE['lang'])) {
$lang = $_COOKIE['lang'];
}
if (empty($lang) || (!in_array($_GET['lang'], $jezici))) {
$trenutni_file = basename($_SERVER['PHP_SELF']);
?>
<META http-equiv="refresh" content="0;URL=http://<?php echo $domena; ?>/<?php echo $trenutni_file; ?>?lang=hr">
<?php
exit();
}

Related

How to set Session Timeout in php?

I'm still new in PHP language and trying out on how to set Session Timeout, which ensure that when user log in to their account, it will limit to few minutes / 1 hour before the account got logout automatically when user log in too long. I refered to this link.
http://bytes.com/topic/php/insights/889606-setting-timeout-php-sessions
index.php
<?php
if(!isset($_SESSION))
{
session_start();
}
$timeout = $_SERVER['REQUEST_TIME'];
/**
* for a 1 minute timeout, specified in seconds
*/
$timeout_duration = 60;
if (isset($_SESSION['LAST_ACTIVITY']) && ($timeout - $_SESSION['LAST_ACTIVITY']) > $timeout_duration) {
session_unset();
session_destroy();
session_start();
}
$_SESSION['LAST_ACTIVITY'] = $timeout;
?>
coupon.php
<?php
// error_reporting(E_ALL); ini_set("display_errors", 1);
session_start();
$timeout = 60; // Number of seconds until it times out.
// Check if the timeout field exists.
if(isset($_SESSION['timeout'])) {
$duration = time() - (int)$_SESSION['timeout'];
if($duration > $timeout) {
// Destroy the session and restart it.
session_destroy();
}
}
// Update the timeout field with the current time.
$_SESSION['timeout'] = time();
// include ('sessionTimeout.php');
if( !isset($_SESSION["loginSuccess"]) ){
echo "<script type='text/javascript'>alert('Login failed!');</script>";
die('<meta http-equiv="refresh" content="0;URL=\'login-redirect.php\'" />');
}
?>
sessionTimeout.php
<?php
function session_start_timeout($timeout=5, $probability=100, $cookie_domain='/') {
// Set the max lifetime
ini_set("session.gc_maxlifetime", $timeout);
// Set the session cookie to timout
ini_set("session.cookie_lifetime", $timeout);
$seperator = strstr(strtoupper(substr(PHP_OS, 0, 3)), "WIN") ? "\\" : "/";
$path = ini_get("session.save_path") . $seperator . "session_" . $timeout . "sec";
if(!file_exists($path)) {
if(!mkdir($path, 600)) {
trigger_error("Failed to create session save path directory '$path'. Check permissions.", E_USER_ERROR);
}
}
ini_set("session.save_path", $path);
// Set the chance to trigger the garbage collection.
ini_set("session.gc_probability", $probability);
ini_set("session.gc_divisor", 100); // Should always be 100
// Start the session!
session_start_timeout(60, 10);
if(isset($_COOKIE[session_name()])) {
setcookie(session_name(), $_COOKIE[session_name()], time() + $timeout, $cookie_domain);
}
}
?>
logout.php
<?php
session_start();
include('config.php');
foreach($_SESSION as $key => $value){
if (strpos($key, $PROJECT_NAME) !== FALSE){
unset($_SESSION[$key]);
}
}
$_SESSION[$PROJECT_NAME . 'logout'] = true;
session_destroy();
//print_r($_SESSION);
header('Location:' . $base_url . 'index');
?>
Am i missing out something? This is because my session timeout doesn't work.
Start a Javascript timer when the page loads and redirect the user to the logout page when the timer expires.
<script type="text/javascript">
setTimeout(function() { window.location.href = "logout.php"; }, 60 * 60 * 1000);
</script>

Set cookies to redirect to the same clicked url next time

I have the following code
index.php:
if(isset($_GET['lang']))
$translate = new Translator($_GET['lang']);
else
$translate = new Translator('en');
when the user make get request like this
index.php?lang=ru
i want the server to remember his request for the next time and redirect him from index.php to index.php?lang=ru
<?php
/*
* first get lang from url and set cookie
*/
if (isset ( $_GET ['lang'] )) {
$lang = $_GET ['lang'];
setcookie ( 'lang', "$lang", time () + 3600 );
}
/*
* second if lang is not set in url then read it from cookie
*/
else if (isset ( $_COOKIE ['lang'] )) {
header ( "location:redirect.php?lang=" . $_COOKIE ['lang'] );
}
/*
* if cookie or url is not set then take default lang value 'en'
*/
else {
$lang = 'en';
header ( "location:redirect.php?lang=" . $lang );
}
?>
Use:
if(isset($_GET['lang']))
{
setcookie("lang", $_GET['lang'], time()+60*60*24*30);
$lang=$_GET['lang'];
}
elseif (isset($_COOKIE['lang']))
{
$lang=$_COOKIE['lang'];
}
else
{
$lang="en";
}
$translate = new Translator($lang);

Converting multi-language function

This is my first ask here so don't judge me if i posted it wrong.
I have this function for my multi-lang support
<?
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 'bg':
$lang_file = 'bg.php';
break;
default:
$lang_file = 'en.php';
}
define('IN_VALID',true);
include_once '_src/lang/'.$lang_file;
?>
It gets languages by &lang=en or &lang=bg .
How i can convert it to get &lang:en instead of &lang=en (if it's possible)
?key1=value1&key2=value2 is standard application/x-www-form-urlencoded format.
To use your format, you should parse it on your own, route that I don't advise.
You can check for isset($_GET["lang:en"]).
But this is not to advice. = is the standard separator for keys and values. There's no need to change it.

Checking cookie and session value

I am working on a multilingual website, and I have a problem now. When the $_GET['setlang'] is empty, language is set to en_US, even if I had ?setlang=pl opened before (which is working fine - language is changing)
empty($_GET['setlang']) ? $_GET['setlang'] = '' : $_GET['setlang'];
switch ($_GET['setlang']) {
case 'en':
$lang = 'en_US';
putenv('LC_ALL='.$lang);
setlocale(LC_ALL, $lang.'.UTF8');
setcookie('lang', $lang, time()+60*60*24*365);
$_SESSION['lang'] = $lang;
$_config['lang'] = $lang;
break;
case 'pl':
$lang = 'pl_PL';
putenv('LC_ALL='.$lang);
setlocale(LC_ALL, $lang.'.UTF8');
setcookie('lang', $lang, time()+60*60*24*365);
$_SESSION['lang'] = $lang;
$_config['lang'] = $lang;
break;
default:
if((isset($_SESSION['lang']) && $_SESSION['lang'] ='en_US') || (isset($_COOKIE['lang']) && $_COOKIE['lang'] = 'en_US')){
$lang = 'en_US';
putenv('LC_ALL='.$lang);
setlocale(LC_ALL, $lang.'.UTF8');
}
else{
$lang = 'pl_PL';
putenv('LC_ALL='.$lang);
setlocale(LC_ALL, $lang.'.UTF8');
}
$_config['lang'] = $lang;
break;
}
$my_name = 'default';
bindtextdomain($my_name,'./locale');
textdomain($my_name);
I can't get this script to change the language to pl_PL after I run ?setlang=pl action. When this get is empty, cookie value is changing to en_US ;/
How should I check it and avoid this problem?
Also I am working with MVC. Does this code seem to be right or should I put some code into model instead of controller?
if((isset($_SESSION['lang']) && $_SESSION['lang'] =='en_US')
|| (isset($_COOKIE['lang']) && $_COOKIE['lang'] == 'en_US'))
make comparisons with == not = this way you assign 'en_US' whatever the $_SESSION["lang"] or $_COOKIE["lang"] is.
Have you started the session? You cannot set or query session variables if you have not.
Use session_start();
$lang = "";
// Check if lang cookie is set
if(isset($_COOKIE['lang']))
{
$lang = $_COOKIE['lang'];
}
// Cookie is not set
else
{
// Get language GET variable
$set_lang = (empty($_GET['setlang'])) ? '' : $_GET['setlang'];
switch($set_lang)
{
case 'en':
$lang = "en_US";
break;
case 'pl':
$lang = "pl_PL";
break;
default:
$lang = "en_US";
break;
}
// Set language cookie
setcookie('lang', $lang, time()+60*60*24*365);
}
// Set locale
putenv('LC_ALL=' . $lang);
setlocale(LC_ALL, $lang . ".UTF8");

$_get and session. Can't get it to work

Can anyone tell me why this doesn't work?
<?php
$lang = $_get["lang"];
if (($lang == "fr"))
{
session_destroy();
session_start();
$_SESSION['lang'] == "fr";
}
if (($lang == "en"))
{
session_destroy();
session_start();
$_SESSION['lang'] == "en";
}
if (isset($_SESSION['lang']))
{
$lang = $_SESSION['lang'];
}
else
{
$lang = "fr";
}
?>
I just can't seem to get it to work and I tried a lot of different things. Just need a direction to the mistake.
It's running on PHP5 on an Apache server if that's any help.
Even without the session I can't even get the $_get to work. With normally is never the case.
$_SESSION['lang'] == "fr";
two equal signs mean comparision operator.
assignment is = (one equal)
One obvious thing is
$_get["lang"];
Variables are case sensitive in PHP. It must be
$_GET["lang"];
if that doesn't solve your problem, you need to describe in detail what exactly doesn't work.
I have re-factored your code to make it easier to work with in the future. As Pekka says and I asked perhaps you need/want $_GET.
<?php
session_start();
$language = $_GET['lang'];
$allowable_languages = array(
'en',
'fr',
);
if(in_array($language, $allowable_languages)) {
$_SESSION['lang'] = $language;
} else {
$_SESSION['lang'] = 'fr';
}
?>
Updated: In answer to your comment:
<?php
session_start();
if(isset($_GET['lang'])) {
$language = $_GET['lang'];
$allowable_languages = array(
'en',
'fr',
);
if(in_array($language, $allowable_languages)) {
$_SESSION['lang'] = $language;
}
}
if(!isset($_SESSION['lang'])) {
$_SESSION['lang'] = 'fr';
}
?>
U just made a single mistake i.e, u are using wrong syntax it should be $_GET['lang'];
Your code doesn't work because session_start() can't be used directly after session_destroy(). Btw, you don't need to destroy session. Just redefine your variable:
$lang = 'fr';
if(isset($_GET['lang']) && in_array($_GET['lang'], array('fr', 'en'))) $lang = $_GET['lang'];
$_SESSION['lang'] = $lang;
For those who thinks the problem is lower case variable - PHP variables are case insensitive.
You are both right. There was a lot of different error. Both the "=" and "==" problem plus the $_GET case sensitive problem.
Here the code i god to work both the $_GET plus the session.
Thanks a lot. I've spend all night trying to find those error plus think i got errorblind.
<?php
$lang = $_GET["lang"];
if (($lang == "fr"))
{
session_destroy();
session_start();
$_SESSION['lang'] = "fr";
}
if (($lang == "en"))
{
session_destroy();
session_start();
$_SESSION['lang'] = "en";
}
if (isset($_SESSION['lang']))
{
$lang = $_SESSION['lang'];
}
else {
$lang = "fr";
}
?>

Categories