How to access a variable across two files

user2688512 picture user2688512 · Sep 3, 2013 · Viewed 36k times · Source

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.....

Answer

MaxEcho picture MaxEcho · Sep 3, 2013

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
?>