How to access a variable across two files
Asked Answered
C

3

15

I have three files - global.php, test.php, test1.php

Global.php

$filename;
$filename = "test";

test.php

$filename = "myfile.jpg";
echo $filename;

test1.php

echo $filename;

I can read this variable from both test and test1 files by include 'global.php';

Now i want to set the value of $filename in test.php and the same value i want to read in test1.php.

I tried with session variables as well but due to two different files i am not able to capture the variable.

How to achieve this........

Thanks for help in advance.....

Camacho answered 3/9, 2013 at 9:42 Comment(3)
Could you show us some code? IMO, there's no reason for this not to work. Also keep in mind that variables are temporary at each reloading of the page will require all the variables to be recreated.Xanthippe
i have added code for all three files.Camacho
Where is your session?Defilade
L
12

Use:

global.php

<?php
if(!session_id()) session_start();
$filename = "test";
if(!isset($_SESSION['filename'])) {
    $_SESSION['filename'] = $filename;
}
?>

test.php

<?php
if(!session_id()) session_start();
//include("global.php");
$_SESSION['filename'] = "new value";
?>

test1.php

<?php
if(!session_id()) session_start();
$filename = $_SESSION['filename'];
echo $filename; //output new value
?>
Luigi answered 3/9, 2013 at 9:55 Comment(2)
Is the include necessary to set the variable name in test.php?Ivory
Thanks @LouieBertoncin , Good findings. No need to include global.php in test.phpLuigi
V
3

I think the best way to understand this is as following:
You have one file index.php whit some variable defined.

$indexVar = 'sometext';

This variable is visible on all index.php file. But like a function, if you include other files, the variable will not be visible unless you specify that this variable has scope global.

You should redefine the scope of this variable in your new file, like this:

global $indexVar;

Then you will be able to acess directly by calling it as you were in your main file. You could use an "echo" in both files, index.php and any other file.

Vogler answered 17/3, 2021 at 10:21 Comment(0)
D
2

First you start session at the top of the page.

Assign your variable into your session.

Check this and Try it your self

test.php

<?php
session_start(); // session start
include("global.php");
$filename = "myfile.jpg";
$_SESSION['samplename']=$filename ; // Session Set
?>

test1.php

<?php
session_start(); // session start
$getvalue = $_SESSION['samplename']; // session get
echo $getvalue;
?>
Defilade answered 3/9, 2013 at 9:49 Comment(2)
after assigning value to $filename i am closing test.php file. so session is not persistingCamacho
@Camacho include function use after session_startDefilade

© 2022 - 2024 — McMap. All rights reserved.