可以在 php 脚本中操作 $_POST 变量并在另一个 php 脚本中表达它


Possible to manipulate $_POST variable in php script and express it in another php script?

我一直在尝试在不使用 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 变量方法,但我发现的东西要么有点复杂,要么涉及我在任何地方启动一大堆会话(在我看来会使我的代码变得混乱)。

> $_POST 是从浏览器传递给服务器的数据内容填充的。当您发送Location标头时,它会导致浏览器加载新页面,但由于它没有表单数据,因此不会传递任何内容。

如果您需要在页面之间传递数据,那么 $_SESSION 是要走的路。所需要的只是在需要访问的页面顶部有一个session_start(),您可以像这样存储$_POST数据:

$_SESSION['postdata'] = $_POST;

检索它成为

$email = $_SESSION['post']['Email'];

另一种方法是将数据作为新表单中的隐藏<input>回显,但这需要提交新表单,我感觉您想要无缝的东西。

另请注意,$_SERVER['HTTP_REFERER'] 不保证准确,甚至不存在。您不应该依赖它来执行生产代码。它可能适用于测试设置中的浏览器,但这并不能保证它适用于其他浏览器。另辟蹊径。

您可以通过使用 javascript 而不是重定向来实现这一点,但通过重定向传递数据的唯一方法是通过 URL、会话或 cookie。

$_POST['errors'] = $tempError;
//redirect back to referring url
?>
<html><head><title></title></head><body>
<form id="temp_form">
<?php
foreach($_POST as $k=>$v) {
?><input type="hidden" name="<?php echo htmlentities($k); ?>" value="<?php echo htmlentities($v); ?>" /><?php 
}
?>
</form>
<script type="text/javascript">
    setTimeout(function() { document.getElementById('temp_form').submit(); },100);
</script>
</body>
</html>
<?php
    die();