How to access a variable across two files

戏子无情 提交于 2019-11-27 02:19:57

问题


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


回答1:


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



回答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;
?>


来源:https://stackoverflow.com/questions/18588972/how-to-access-a-variable-across-two-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!