问题描述
我有两个文件,一个名为functions.PHP,另一个名为error.PHP,我想做的是在functions.PHP中运行一些程序,覆盖错误变量,调用 error.PHP 文件并在那里显示错误,但我似乎无法正确获取变量的范围。我需要一些帮助并解释我的代码有什么问题。
在我的 functions.PHP 文件中,我有这样的内容:
<?PHP
$error = false;
$errorMsg = 'Some text';
function register ($email,$password) {
//Calling global error variables
global $error,$errorMsg;
//MysqL query to check if email exists in DB
if (/*email exists condition*/) {
//Overwrite error variables
$error = true;
$errorMsg = 'Email already exists';
//Redirect to error page
header ("Location: error.PHP");
}
else {
//Continue adding values to DB
}
} ?>
然后在我的 error.PHP 文件中,我有一些像这样的速记 PHP 代码:
<?PHP require_once (functions.PHP); ?>
<?PHP if($error): ?>
<h2>An error occurred: <?PHP echo $errorMsg; ?></h2>
<?PHP elseif(!$error): ?>
<h2>No error: All operations completed successfully</h2>
<?PHP else: ?>
<h2>An unkNown error occurred</h2>
<?PHP endif; ?>
现在,当我提供一个已存在于数据库中的条目时,页面会重定向,但错误变量似乎未更新,新打开的 error.PHP 页面将输出显示为:
无错误:所有操作成功完成
解决方法
您有一个重定向标头 ("Location: error.php") ,所以实际上您正在执行两个 http 请求 => 两个不同的 php 进程(执行的页面),该变量将不可见. 最简单的方法是将变量的值存储在第一页的 $_SESSION 中,并在第二页中读取它。 见PHP Pass variable to next page
您还应该关注https://www.php.net/manual/en/reserved.variables.session.php
,您可以添加您的错误、代码和/或消息作为重定向的查询字符串。
ApplicanteeTO applicanteeTO = null;
if(applicanteeNRIC != null && !applicanteeNRIC.equals("")){
if(!populationId.equals(Constants.POPTYPE1) && !populationId.equals(Constants.POPTYPE2)) {
applicanteeTO = //retrieve from db
}
}
log.debug("applicanteeTO details: " + applicanteeTO);
if(applicanteeTO != null){
// do logic
}
输出:
The method initForm() in SingleReplacementController.java can crash the program by dereferencing a null-pointer on line 110.
将查询字符串附加到您的重定向位置。
将代码参数用于路径的示例,例如:ApplicanteeTO applicanteeTO;
if(applicanteeNRIC != null && !applicanteeNRIC.equals("")){
if(!populationId.equals(Constants.POPTYPE1) && !populationId.equals(Constants.POPTYPE2)) {
applicanteeTO = //retrieve from db
}
} else {
applicanteeTO = null;
}
log.debug("applicanteeTO details: " + applicanteeTO);
if(applicanteeTO != null){
// do logic
}
。关于 error.php:
<?php
$qs = http_build_query(
[
'error' => true,'errorMsg' => 'Email already exists'
]
);
var_dump($qs);