我希望在执行php函数后重定向到页面,并同时提交带有方法POST
的html表单。
我找到了许多GET
的解决方案,但我希望使用POST
处理此问题。
答案 0 :(得分:0)
您可以使用cUrl
发送所需的POST数据,然后进行重定向。
在网上查看:“php curl”。
答案 1 :(得分:0)
让你的form action
指向要执行你的功能的php文档,然后最后放置header("location: your_location_file.php");
第一步 - 将表格提交给functions.php
第二步 - 做任何你需要处理的提交数据
第三步 - 重定向
示例:
<form method="post" action="functions.php">
...
</form>
的functions.php
<?php
...
all your code
...
header("location: your_location_file.php");
?>
答案 2 :(得分:0)
如果您不想依赖curl,Javascript可以提供帮助。有这个铺设。传入$ _POST或您要发布的数据数组。添加错误/参数检查。
function http_post_redirect($url='', $data=array(), $doc=true) {
$data = json_encode($data);
if($doc) { echo "<html><head></head><body>"; }
echo "
<script type='text/javascript'>
var data = eval('(' + '$data' + ')');
var jsForm = document.createElement('form');
jsForm.method = 'post';
jsForm.action = '$url';
for (var name in data) {
var jsInput = document.createElement('input');
jsInput.setAttribute('type', 'hidden');
jsInput.setAttribute('name', name);
jsInput.setAttribute('value', data[name]);
jsForm.appendChild(jsInput);
}
document.body.appendChild(jsForm);
jsForm.submit();
</script>";
if($doc) { echo "</body></html>"; }
exit;
}
答案 3 :(得分:0)
您可以使用会话来保存POST数据。
我目前正在使用如下代码。在我的第一页加载时,检查$ _POST数据。如果它包含数据库中已有的某些值,则会重定向到这些值的页面。
// This could be part of the same script as below, or a different script.
session_start();
if($_POST['my_value'] && valueExistsInMyDb($_POST['my_value']) ) { // check my db to see if this is an existing value
$id = getIdOfMyValue($_POST['my_value']); // e.g. '4'
$_SESSION['POST'] = $_POST; // take ALL post data and save it in the session variable
header("location: your.php?myvalue=" . $id); // redirect to bookmarkable target page where $_GET variable matches what was posted.
exit(); // ensure no other code is executed in this script after header is issued.
}
然后你的另一个文件(或者甚至是同一个文件)可以这样做:
// your.php?myvalue=4
if(isset($_SESSION) && array_key_exists('POST',$_SESSION)) {
$_POST = $_SESSION['POST']; // creates or overwrites your $_POST array with data from the session. The rest of your script won't be able to tell that it's not a real $_POST, which may or may not be what you want.
unset($_SESSION['POST']); // you probably want to remove the data from the session.
}
// now your myvalue=4 is stored in GET, and you can handle the rest of the POST data as you like
我不知道这是否是最佳解决方案,但到目前为止它似乎对我有用。我几天前刚刚写了代码,还没有测试过所有方面。
另一个选择是使用HTML5更改地址栏。无需重定向。但缺点是显然只有“现代Webkit浏览器”才能使用它。