PHP-变量值的奇怪变化
a编写了以下代码:PHP-变量值的奇怪变化,php,variables,Php,Variables,a编写了以下代码: <?php require("../../config.php"); require("../php/funct.php"); try { $pdo = new PDO('mysql:host='.DB_HOST.';dbname='.DB_TABL.';', DB_AUSER, DB_APASS); } catch(PDOException $e) { echo 'Error: ' . $e->getMessage(); } $idee=uni
<?php
require("../../config.php");
require("../php/funct.php");
try {
$pdo = new PDO('mysql:host='.DB_HOST.';dbname='.DB_TABL.';', DB_AUSER, DB_APASS);
}
catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
$idee=unique_id();
$insystem=true;
include('session_check.php');
unset($insystem);
print($sesja); ///// SECOND PRINT()
if($sesja!=1) {
die("Session error");
exit;
} else {
//some other code
}
问题是:第一次打印(来自session_check.php)打印出1—期望值是多少,但主脚本中的第二次打印输出0—这对我来说很奇怪,因为$sesja变量在这两次打印之间没有更改
出什么问题了?发生这种情况是因为
$sesja
首先设置在包含的代码中,并且仅存在于其中。当代码执行返回到主PHP脚本时,$sesja
超出范围并被遗忘
要解决此问题,需要设置
$sesja=0
包含之前的某个位置。然后,包含的代码将继承作用域并修改正确的变量。您的代码太复杂,很难跟踪它。您应该将其拆分为几个函数,并分别测试它们中的每一个。此外,请尝试使用调试器(设置起来并不太困难):它对这种情况最有帮助。Czesc
<?php
if(isset($insystem) && $insystem) {
if(!isset($_COOKIE['seid'])) {
setcookie('seid', $idee, time() + COOKIELIFE);
$sesja=0;
} else {
setcookie('seid', $_COOKIE['seid'], time() + COOKIELIFE);
$dane=$pdo->prepare('SELECT s.id, s.ip, s.czas, s.prawa, p.nick, p.id FROM sessions s JOIN pracownicy p ON s.Pracownicy_id=p.id WHERE s.id=:id');
$dane->bindValue(':id',$_COOKIE['seid'], PDO::PARAM_STR);
$dane->execute();
$dsesji = $dane -> fetch();
$dane->closeCursor();
unset($dane);
if($dsesji!==false) {
if(isset($_GET['lo']) && ($_GET['lo']==='lo') && isset($indeks) && $indeks) {
$usun=$pdo->prepare('DELETE FROM sessions WHERE id=:id');
$usun->bindValue(':id',$_COOKIE['seid'], PDO::PARAM_STR);
$usun->execute();
unset($usun);
setcookie('seid', 'abc', time() - 42000);
header("Location: index.php");
}
$sesja=1;
$_nick=$dsesji['nick'];
$_Pracownicy_id=$dsesji['id'];
$_prawa=explode('|',$dsesji['prawa']);
unset($_prawa[count($_prawa)-1]);
if($dsesji['ip']!=$_SERVER['REMOTE_ADDR']) {
$usun=$pdo->prepare('DELETE FROM sessions WHERE id=:id');
$usun->bindValue(':id',$_COOKIE['seid'], PDO::PARAM_STR);
$usun->execute();
unset($usun);
setcookie('seid', 'abc', time() - 42000);
header("Location: index.php?lo=bs");
exit;
}
$teraz=time();
$roznica=$teraz-$dsesji['czas'];
if($roznica>(TIMEOUT*60)) {
$usun=$pdo->prepare('DELETE FROM sessions WHERE id=:id');
$usun->bindValue(':id',$_COOKIE['seid'], PDO::PARAM_STR);
$usun->execute();
unset($usun);
setcookie('seid', 'abc', time() - 42000);
header("Location: index.php?lo=to");
exit;
}
if($sesja!=0) {
$idee=unique_id();
setcookie('seid', $idee, time() + COOKIELIFE);
$dane=$pdo->prepare('UPDATE sessions SET id=:nowyid WHERE id=:id');
$dane->bindValue(':nowyid',$idee, PDO::PARAM_STR);
$dane->bindValue(':id',$_COOKIE['seid'], PDO::PARAM_STR);
$dane->execute();
unset($dane);
$_CURR_SID=$idee;
unset($idee);
}
print($sesja); ///// FIRST PRINT()
} else {
$sesja=0;
}
}
} else {
die('aerr1');
}
?>