Yos*_*ahu 47 html php post header
我正在使用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>
Run Code Online (Sandbox Code Playgroud)
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');
}
Run Code Online (Sandbox Code Playgroud)
如果出现错误,我需要将其POST回第一页.我不能使用GET,因为输入太大了.如果可能的话,我不想使用SESSION.这可能吗?
bow*_*ior 26
// 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;
}
Run Code Online (Sandbox Code Playgroud)
dec*_*eze 20
如果您不想使用会话,您唯一可以做的就是POST到同一页面.无论如何,哪种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>
Run Code Online (Sandbox Code Playgroud)
这可以变得更优雅,但你明白了......
无法将POST重定向到其他位置.当您发出POSTED请求时,浏览器将从服务器获得响应,然后POST完成.之后的一切都是新的要求.当您在其中指定位置标题时,浏览器将始终使用GET方法来获取下一页.
您可以使用一些Ajax在后台提交表单.这样你的表格价值保持不变.如果服务器接受,您仍然可以重定向到其他页面.如果服务器不接受,则可以显示错误消息,让用户更正输入并再次发送.