如何在PHP中的包含函数后检索变量

时间:2019-02-09 15:20:30

标签: php variables session-variables

我已经使用include函数在页面上添加了用户限制,但是此操作清空了我的变量,因此,登录后,由于此原因未显示结果,如何在脚本中保留变量?我以为会议是一种方式,但它不起作用。

<?php
$trim=$_POST['trim'];
$estu=$_POST['estu'];
session_start();
$_SESSION['trim'] = $trim;
$_SESSION['estu'] = $estu;

if($trim == "RJ") {
echo "<h2>Login required!</h2>";
include ("../admin/accesusers.php");
}

$trim = $_SESSION['trim'];
$estu = $_SESSION['estu'];
echo "Your choices are ".$trim." and ".$estu; 
?>

所以最后一个echo的输出是... 您的选择是 ... ...因为当$trim == "RJ"的结果很好时,例如您的选择是 T1 3323

文件accesusers.php:

<?php
$db = new mysqli('localhost','usr','pass','Dbase');
include_once("login.php");
$_auth = new auth($db); // Anything past here is logged in
$username = $_auth->getUsername();
?>

login.php 文件中,唯一提及 SESSION 的变量就是这个变量,难道这就是搞砸了吗?

define('LOGIN_SESSION_EXPIRED',-8);
....
LOGIN_SESSION_EXPIRED=>'<br /><h3>Your session is outdated!</h3>',
....
die($this->form(LOGIN_SESSION_EXPIRED,'signin'));

1 个答案:

答案 0 :(得分:0)

好,我终于解决了。我已经意识到,只有当include()位于if内时,变量才会丢失,并且$_SESSION必须从$_POST而不是从{变量($trim)来传播此值;所以我以这种方式进行了解决:

文件1.php

<?php
$trim = $_POST['trim'];
$estu = $_POST['estu'];
if($trim == 'RJ') {
        header( 'Location: 2.php' ) ;
        session_start();
$_SESSION['estu'] = $_POST['estu'];
$_SESSION['trim'] = $_POST['trim'];
} else {
echo "<p>Your choices are ".$trim." and ".$estu."</p>";
}
?>

文件2.php

<?php
session_start();
$estu = $_SESSION['estu'];
$trim = $_SESSION['trim'];
echo "<h2>Login required!</h2>";
include ("../admin/accesusers.php");
echo "<p>Your choices are ".$trim." and ".$estu."</p>";
?>

所以现在输出为“ 您的选择是 RJ 3323