PHP header() 使用 POST 变量重定向

2022-08-30 10:11:06

我正在使用PHP,我正在制作一个表单发布到的操作页面。该页面检查错误,然后如果一切正常,则会将它们重定向到已发布数据的页面。如果没有,我需要将它们重定向回它们所在的页面,其中包含错误和POST变量。以下是它的工作原理的要点。

HTML 看起来像这样...

<form name="example" action="action.php" method="POST">
  <input type="text" name="one">
  <input type="text" name="two">
  <input type="text" name="three">
  <input type="submit" value="Submit!">
</form>

动作.php看起来像这样...

if(error_check($_POST['one']) == true){
    header('Location: form.php');
    // Here is where I need the data to POST back to the form page.
} else {
    // function to insert data into database
    header('Location: posted.php');
}

如果出现错误,我需要它才能开机自检回第一页。我不能使用GET,因为输入太大了。如果可能的话,我不想使用SESSION。这可能吗?


答案 1
// from http://wezfurlong.org/blog/2006/nov/http-post-from-php-without-curl
function do_post_request($url, $data, $optional_headers = null)
{
  $params = array('http' => array(
              'method' => 'POST',
              'content' => $data
            ));
  if ($optional_headers !== null) {
    $params['http']['header'] = $optional_headers;
  }
  $ctx = stream_context_create($params);
  $fp = @fopen($url, 'rb', false, $ctx);
  if (!$fp) {
    throw new Exception("Problem with $url, $php_errormsg");
  }
  $response = @stream_get_contents($fp);
  if ($response === false) {
    throw new Exception("Problem reading data from $url, $php_errormsg");
  }
  return $response;
}

答案 2

如果您不想使用会话,您唯一能做的就是发布到同一页面。无论如何,哪个IMO是最好的解决方案。

// form.php

<?php

    if (!empty($_POST['submit'])) {
        // validate

        if ($allGood) {
            // put data into database or whatever needs to be done

            header('Location: nextpage.php');
            exit;
        }
    }

?>

<form action="form.php">
    <input name="foo" value="<?php if (!empty($_POST['foo'])) echo htmlentities($_POST['foo']); ?>">
    ...
</form>

这可以变得更优雅,但你明白了...


推荐