Pass an array from one file to another using include - php

How to pass an array from one file to another using include using PHP language?
I have one file with some language array(language/langen.php):
global $lang;
$lang['Here'] = 'Here';
$lang['Date'] = "Date";
In other file I have:
include base_url().'language/lang'.$_COOKIE['lang'].'.php';
var_dump($lang);
*(My mistake by coping code - true is var_dump($lang))*
But it shows me an error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: lang
How to solve this problem and what did I do wrong?

First of all:
You should never use cookie value directly in include statement - its pretty easy to make fake cookie and mess up in your application.
I suppose you just don't have cookie with name lang or variable $lang has never been initialized before.
To check if cookie exists and is in correct format you can do like that:
// set default lang code
$langCode = 'en';
// check if cookie exists and if contains string build from 2 characters from range a-z
// check also if file exists
if (isset($_COOKIE['lang'] && preg_match('/^[a-z]{2}$/', $_COOKIE['lang']) &&
file_exists(base_url().'language/lang'.$_COOKIE['lang'].'.php')) {
$langCode = $_COOKIE['lang'];
}
include base_url().'language/lang'.$langCode.'.php';
in included file you should check if variable $lang exists
if (!isset($lang)) $lang = array();
$lang['Here'] = 'Here';
$lang['Date'] = "Date";
also I think using global here is pointless as from your example it looks like its the same scope.
anyway for me much cleaner solution would be:
// first_file.php
$langCode = 'en';
if (isset($_COOKIE['lang'] && preg_match('/^[a-z]{2}$/', $_COOKIE['lang']) &&
file_exists(base_url().'language/lang'.$_COOKIE['lang'].'.php')) {
$langCode = $_COOKIE['lang'];
}
$lang = include base_url().'language/lang'.$langCode.'.php';
// langen.php
return array(
'Date' => 'Date',
'Here' => 'Here',
);
EDIT
One more thing - If base_url() is returning web URL (like http://example.com...) then it is also wrong (and also can cause problem as langen.php will contain at least Notice message when included this way) - should be included with valid file path

Shouldn't it be?
include base_url().'language/lang'.$_COOKIE['lang']['Here'].'.php';
Or else it would just return array()

First of all, I don't see the point of var-dumping variable $data, if there is no such thing in code you posted. If you have a cookie called "lang" in your browser, then you should be fine. You could always check this by
var_dump($GLOBALS['lang']);
in your code. It should print the array of values from your lang*.php file.

Related

PHP declared variable, to another file that's included via function

I have some kind of problem, but i don't get it.. I have an function for including/requiring files, which check is file already included and does exists:
function __include($fileclass, $is_required=false) {
static $already_included = array();
// checking is set extension of php file, if not append it.
if (substr($fileclass,-4)!=".php") $fileclass = $fileclass.".php";
// if already included return;
if (isset($already_included[$fileclass])) return true;
// check if file exists:
if (file_exists($fileclass)) {
if (!$is_required) include $fileclass;
else require $fileclass;
$already_included[$fileclass] = 1;
return true;
}
else {
if ($is_required) die("can't find required file");
return false;
}
}
And it works good, but when i started to work on the project, i've used it to include a file, which uses variable from parent file (the one that included it), but it drops notice Notice: Undefined variable: VARIABLE_NAME.
So to be clear at coding:
I have two files file_parent.php and file_child.php, what I've tried:
file_parent.php:
function __include($fileclass, $is_required=false) { /** i've mentioned it above **/ }
class __CONNECTION {
private $test;
public function __construct() {
$this->test = "SOMETHING";
}
};
$Connect = new __CONNECTION();
// here i used it to include the children file:
__include('file_child.php');
file_child.php:
print_r($Connect);
And i get Notice: Undefined variable: Connect.
When i change at file_parent.php my function include:
__include('file_child.php');
to standard include:
include 'file_child.php';
Everything will work fine, variable is defined and will be printed.
I guess there's some problem with function, but could someone explain what's the real reason for happening this, and is there a possible repair to fix it to including/requiring works through function and to not lose variables from previous files.
Thanks!
Well, how do i see, when i printed all defined variables (get_defined_vars()), i got this:
Array
(
[fileclass] => test_file2.php
[is_required] =>
[already_included] => Array
(
)
)
So that means the variables are passed, but only one that exists within function (because the function is temporary), so i could make it work to pass variables to function, but as it's not the only variable I need so I am gonna use one of two way:
global as #Tom Doodler said in comment, and later catch it with $GLOBALS
or use function to do checks and return just a path if exists/or empty string if file doesn't exists and then just include/require it.
Thanks everyone.
I will not accept this answer, so if someone could better explain the way function behaves in this solution, i will accept that.

Un-setting variable in URL gives error

I've recently been developing a multi-lingual website. I've got a slight problem though.
Every time a button is clicked the language variable needs to change. i did this using the anchor tag (i.e English ).
The problem arises when other variables besides the language are added to the URL. I would like to redirect the page without getting rid of other variables and just changing the lang variable. So if the url contains "var1=value&var2=value&lang=En", I would like to alter the lang variable and keep the rest as they are. The lang variable can have 3 values: En, Az, Ru.
The method I tried so far:
function URI_ADD_AZ(){
$URI = $_SERVER['REQUEST_URI'];
if(isset($_GET['lang'])){
$lang = $_GET['lang'];
unset($lang);
}
$new_URI = $URI . '?lang=Az';
return $new_URI;
}
Azeri
The problem:
Everytime the button is clicked the lang variable just gets added to the url not altered:
/?lang=Az?lang=Az?lang=Az?lang=Az
How can I make sure it does not keep getting repeated and avoid redirect loops?
The URI_ADD_AZ function posted in the question does not overwrite or remove preexisting occurrences of lang=* in the Query String, therefore duplication of "langs" in the URL. Also there is no handling of the requirement for ? or & depending on location of the key=value pair in the query string.
Here, to simplify things and limit the working string and therefore potential for introducing errors, the $_SERVER var QUERY_STRING is pulled, rather than the entire REQUEST_URI, and PHP_SELF is then prepended to the HREF value.
First thing here is to remove the lang=* including the & depending on it's position. A conditional reference is used to remove the trailing & only if the match is found at the beginning of the string.
Next $lang is retrieved from the $_GET var and validated. And if there's a valid $lang it is appended to the query string taking into consideration whether & is needed or not.
Finally, if not empty, the resulting query string is prepended with ? and returned.
function URI_ADD_AZ() {
$QS = preg_replace('/((^)|&)lang=[^&]*(?(2)&)?/', '', $_SERVER['QUERY_STRING']);
$lang = ( isset($_GET['lang']) && in_array($_GET['lang'], array('En','Az','Ru')) )? 'lang=' . $_GET['lang']: '';
if ( '' != $lang ) {
if ( '' == $QS ) { $QS = $lang; }
else { $QS .= "&$lang"; }
}
if ( '' != $QS ) {
return '?' . $QS;
}
}
Azeri
Simply provide Complete URL :-
Azeri
or, if you want to do it without reloading of page, you will have to use "jquery.history.js" file.
https://github.com/browserstate/history.js
History.pushState(null, 'title of my website', "?lang=<?php URI_ADD_AZ(); ?>);
Thanks

PHP - Reloading URL with a GET variable

I would like to ensure that a $_GET variable is set to the value of another variable in my URL. If not then i would like to reload the page/url to show a set variable. This is the code im using:
session_start();
$openfile = $_SESSION['openfile'];
//check if $GET variable isset to the current $SESSION variable
if($_GET['file'] !== $_SESSION['openfile'] && !empty($_SESSION['openfile'])){
//if not then create new URL string
$hloc = basename($_SERVER['PHP_SELF']).'?file='.$openfile;
//change location to new URL string
header("Location: $hloc");
}
i dont understand why it doesn't work.
Any help would be great. Thanks.
edit: the problem is that the url doesn't reflect that of what the header info should be. this fixes itself fine if the page is then reloaded again. however, this is clearly not what I want.
if(isset($_GET['file'])) {
//its set means value is not equal to null or false
} else {
//its not set so redirect
}
http://php.net/manual/en/function.isset.php
Can you provide an example URL so we can see if that is coking it? Barring that, try this instead. Note how the $hloc is now outside the quotes:
session_start();
//check if $GET variable isset to the current $SESSION variable
if($_GET['file'] !== $_SESSION['openfile'] && !empty($_SESSION['openfile'])){
//if not then create new URL string
$hloc = basename($_SERVER['PHP_SELF']).'?file='.$openfile;
//change location to new URL string
header("Location: " . $hloc);
}
There is a mistake. Undefined variable: openfile.
Change this line
$hloc = basename($_SERVER['PHP_SELF']).'?file='.$openfile;
to
$hloc = basename($_SERVER['PHP_SELF']).'?file='.$_SESSION['openfile'];
As $openvariable is set(according to poster comment), so only fault is:
Either SESSION variable or GET variable is not set.Since the following code works perfectly.
<?php
session_start();
$_SESSION['openfile']='foo';
$_GET['file']='bar';
$openfile = $_SESSION['openfile'];
//check if $GET variable isset to the current $SESSION variable
if($_GET['file'] !== $_SESSION['openfile'] && !empty($_SESSION['openfile'])){
//if not then create new URL string
$hloc = basename($_SERVER['PHP_SELF']).'?file='.$openfile;
//change location to new URL string
header("Location: $hloc");
}
?>
As syntactically your code looks perfect,thus check properly whether Both GET Variable and Session Variable is set or not.
First Comment this statement header("Location: $hloc"); temporarily.
Put:
echo $_GET['file'];
echo $_SESSION['openfile'];
before if condition and check the output.It will help you to trace and know bug.
i found the problem.
it was due to having incorrect header information further down the script.

Translating a web page using Array function

I want to use the array function of PHP to translate a website. I have created PHP files with arrays in them for all the text to be translated.
<?php
//ESPANOL
$lang = array(
'work' => 'Trabajo'
'packaging' => 'Empaque'
);
And then I am calling them inside my nav.php file, and will in the content section too.
<?php include('includes/languages/es.php'); ?>
<?php echo $lang['work']; ?>
All pretty straight forward.
What I want to know is how to switch between these array files without editing the HTML, so that I don't have to link to another 'index_es.php' etc. I understand that the link would be something like this, but I don't know how this is going to work.
English
I'm guessing I need to include another file that includes the language files and then the link can choose from them but I don't know what the code would be for this.
Would it involve including a 'lang_directory' above the link and then somehow including from there??
**Also I would like to avoid using Zend/Gettext translation becuase I want to learn this inside out.
You can make another dimension containing the target language. Then pass a GET parameter to select that language. If the language isn't recognized you can fallback to English. Here's a sample.
$languages = array(
'en' => array(
'work' => 'work',
'packaging' => 'packaging'
),
'es' => array(
'work' => 'Trabajo',
'packaging' => 'Empaque'
),
);
// default language to use when the requested isn't found
$defaultLanguage = 'en';
// language requested via GET
$requested = $_GET['locale'];
// use the requested language if it exists, otherwise the default language
$language = isset($languages[$requested]) ? $requested : $defaultLanguage;
// our translations
$translation = $languages[$language];
// "work" translated based on the language
echo $translation['work'];
And the link for Español would look like this.
index.php?locale=es
I'd keep your array system, correct the links into something like index.php?lang=en and then include your file depending on the lang parameter:
if ( isset($_GET['lang']) && file_exists('includes/languages/'.$_GET['lang'].'.php') ){
include_once('includes/languages/'.$_GET['lang'].'.php');
}
And if you want to keep the language parameter in your session, do something like this:
if ( isset($_GET['lang']) && file_exists('includes/languages/'.$_GET['lang'].'.php') ){
$_SESSION['lang'] = $_GET['lang'];
}
if ( !isset($_SESSION['lang']) ){
// Default language
$_SESSION['lang'] = 'en';
}
include_once('includes/languages/'.$_SESSION['lang'].'.php');
One way to do this is by using sessions.
Make a lang.php file that will be used to change between languages.
<?php
//Start session
session_start();
//Do we get a lang variable
if (isset($_GET['lang'])) {
//Make sure we only get the lang filename
$lang = basename($_GET['lang']);
//If the file exists, then save it to session
if (file_exists('includes/languages/' . $lang . '.php'))
$_SESSION['lang'] = $lang;
}
//If the client were refered here (via hyperlink) send them back
if (isset($_SERVER['HTTP_REFERER']))
header('location: ' + $_SERVER['HTTP_REFERER']);
?>
In the header of the files you want multiple languages, insert.
<?php
//Start session
session_start();
//Default language
$lang = 'english';
//If the client have set a language, use that instead
if (isset($_SESSION['lang']))
$lang = $_SESSION['lang'];
//Load language file
include('includes/languages/' . $lang . '.php');
?>
The links to change language will then be like this:
Español|English
Out can also take the code from the lang.php file and put in a included file that will be loaded before the inclusion of language file and remove the HTTP_REFERER redirection.
The links to change language will then be like this:
Español|English

Losing a session variable between one page with codeigniter session library

In my code i am trying to store a variable between two pages but i either get a string return "images" or 0... or nothing- tried casting it.. echoing in on one page works and displays correct number but as soon as you click through the view to the next page- its lost- i tried turning on cs_sessions in the db and made no difference
<?php
public function carconfirm($car_id = '')
{
if(empty($car_id))
{
redirect('welcome');
}
$this->load->model('mcars');
$car = $this->mcars->getCar($car_id);
$data['car'] = $car->row_array();
$car_id = (int) $car_id;
$this->session->set_userdata('flappy', $car_id);
echo $car_id;
//insert details
//display details
$this->load->view('phps/carconfirm',$data);
}
function confirm()
{
//get vars
$time_slot = $this->session->userdata('slot');
$person_id = $this->session->userdata('person_id');
$car_id = $this->session->userdata('flappy');
$insert_array = array( 'slot'=> $time_slot ,
'car'=> $car_id,
'person_id'=> $person_id
);
print_r($insert_array);
$this->load->model('mbooking');
$result = $this->mbooking->addbooking($insert_array);
if($result)
{
redirect('welcome/options');
}
}
?>
the variable I'm losing is flappy- i changed the name to see if that was the problem
Finally, I fixed this. Using this answer in SO too : codeigniter setting session variable with a variable not working, I scan my js/css for missing resources. Turn out that, my thickbox.js refer to loadingAnimation.gif in, yes, images folder. That's where the images come. Having fix the missing file, the sesion variabel working just fine.
Not sure, why CI replace (maybe) last added session variabel using this, but maybe it's because CI is not using $_SESSION global variabel. CMIIW. I use this article as a hint : http://outraider.com/frameworks/why-your-session-variables-fail-in-codeigniter-how-to-fix-them/

Categories