html-PHP header()使用POST变量重定向
这个问题已经在这里有了答案:
带重定向参数的PHP重定向 9个答案
我正在使用PHP,并且正在制作表单要发布到的操作页面。 该页面检查错误,然后,如果一切正常,则将其重定向到已发布数据的页面。 如果没有,我需要将它们重定向到错误和POST变量所在的页面。 这是其工作原理的要点。
HTML看起来像这样...
action.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。这可能吗?
5个解决方案
26 votes
// 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;
}
bowsersenior answered 2020-06-24T22:18:32Z
20 votes
如果您不想使用会话,则只能执行POST到同一页面的操作。 无论哪种IMO是最好的解决方案。
// form.php
if (!empty($_POST['submit'])) {
// validate
if ($allGood) {
// put data into database or whatever needs to be done
header('Location: nextpage.php');
exit;
}
}
?>
...
可以使它变得更优雅,但是您会想到的...
deceze answered 2020-06-24T22:18:16Z
6 votes
无法将POST重定向到其他地方。 当您发布请求后,浏览器将从服务器获得响应,然后完成发布。 此后的所有内容都是新请求。 当您在其中指定位置标头时,浏览器将始终使用GET方法来获取下一页。
您可以使用一些Ajax在后台提交表单。 这样,您的表单值将保持不变。 如果服务器接受,您仍然可以重定向到其他页面。 如果服务器不接受,则可以显示错误消息,让用户更正输入并再次发送。
Jan Thomä answered 2020-06-24T22:18:57Z
0 votes
在通过POST发送表单之前,先验证表单数据是有益的。 您应该创建一个JavaScript函数来检查表单中的错误,然后发送该表单。 这样可以防止数据反复发送,这可能会减慢浏览器的速度并使用服务器上的传输量。
编辑:
如果出于安全考虑,执行AJAX请求以验证数据将是最好的方法。 来自AJAX请求的响应将确定是否应提交表单。
Evan Mulawski answered 2020-06-24T22:19:26Z
0 votes
对您的内容使用一个smarty模板,然后将POST数组设置为smarty数组并打开模板。 在模板中,只需回显数组即可,如果它通过了:
if(correct){
header("Location: passed.php");
} else {
$smarty->assign("variables", $_POST);
$smarty->display("register_error.php");
exit;
}
我还没有尝试过,但是我将尝试将其作为解决方案,并让您知道我的发现。 但是,当然,此方法假定您使用的是smarty。
如果不是这样,您可以在错误页面上在那里重新创建表单并将信息回显到表单中,或者您可以从get中发送回不重要的数据并获取它
例如
register.php?name=mr_jones&address==......
echo $_GET[name];
Derrick answered 2020-06-24T22:19:59Z