我一直在尝试在不使用 url 的情况下进行表单验证。所以我想我会在我的表单中创建一个隐藏字段并将其发送到我的验证 php 脚本。我希望我能够做的是将表单中的任何错误设置到这个隐藏字段并将其返回。但是,一旦我离开范围,它就会破坏我设置的任何内容。我认为 $_POST 具有全球范围?也许我声明我将隐藏字段设置错了?我把代码放在下面。
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/config/databaseConnect.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/config/functions.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/models/users.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/models/userDetails.php';
//get the refering url to be used to redirect
$refUrl = $_SERVER['HTTP_REFERER'];
if(isset($_POST['register'])){
//declare a temp error array
$tempError;
//check if the form is empty
if(empty($_POST['Email'])&&empty($_POST['Email Confirmation'])&&empty($_POST['Password'])&&empty($_POST['Password Confirmation'])
&&empty($_POST['Stage Name'])&&empty($_POST['Main Club'])){
$tempError = 'Please fill in the form.';
}else{
//set variables
}
if(!empty($tempError)){
//start a session to declare session errors
$_POST['errors'] = $tempError;
//redirect back to referring url
header('Location:'.$refUrl);
exit();
}else{
//log user in and redirect to member home page
}
}
基本表单(我排除了输入字段,因为它真的很长)
<div class="col-md-6 well">
<span class="jsError"></span><?php if(isset($_POST['errors'])){ $errors = $_POST['errors']; } if(!empty($errors)){ echo '<p class="alert alert-danger text-center">'.$errors.'</p>'; } ?>
<form class="form-horizontal" role="form" method="post" action="controllers/registrationController.php" id="registration">
<input type="hidden" name="errors" value="<?php if(isset($_POST['errors'])){echo $_POST['errors']; } ?>">
</form>
我也研究过使用 $_SESSION 变量方法,但我发现的东西要么有点复杂,要么让我在任何地方开始一大堆会话(在我看来会让我的代码变得混乱)。