如何使用 PHP header() 函数发布到页面? [英] How do you POST to a page using the PHP header() function?

查看:24
本文介绍了如何使用 PHP header() 函数发布到页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 here 上找到了以下代码,我认为它有什么作用我想要,但它不起作用:

I found the following code on here that I think does what I want, but it doesn't work:

$host = "www.example.com";
$path = "/path/to/script.php";
$data = "data1=value1&data2=value2";
$data = urlencode($data);

header("POST $path HTTP/1.1
");
header("Host: $host
");
header("Content-type: application/x-www-form-urlencoded
");
header("Content-length: " . strlen($data) . "
");
header("Connection: close

");
header($data);

我希望在不将用户发送到中间页面然后使用 JavaScript 重定向他们的情况下发布表单数据.我也不想使用 GET,所以使用后退按钮不是那么容易.

I'm looking to post form data without sending users to a middle page and then using JavaScript to redirect them. I also don't want to use GET so it isn't as easy to use the back button.

这段代码有问题吗?或者有更好的方法吗?

Is there something wrong with this code? Or is there a better method?

编辑 我在想标题函数会做什么.我想我可以让浏览器将数据发送回服务器,但这不是它的本意.相反,我在我的代码中找到了一种完全不需要发布的方法(不会破坏并且只是继续切换中的下一个案例).

Edit I was thinking of what the header function would do. I was thinking I could get the browser to post back to the server with the data, but this isn't what it's meant to do. Instead, I found a way in my code to avoid the need for a post at all (not breaking and just continuing onto the next case within the switch).

推荐答案

header 函数用于将 HTTP 响应头返回给用户(即您不能使用它来创建请求头.

The header function is used to send HTTP response headers back to the user (i.e. you cannot use it to create request headers.

请问你为什么要这样做?当您可以就在那里然后以某种方式对数据采取行动时,为什么还要模拟 POST 请求?我当然假设 script.php 驻留在您的服务器上.

May I ask why are you doing this? Why simulate a POST request when you can just right there and then act on the data someway? I'm assuming of course script.php resides on your server.

要创建 POST 请求,请使用 fsockopen() 打开一个到主机的 TCP 连接,然后在从 fsockopen() 返回的处理程序上使用 fwrite(),其值与您在 OP 的标头函数中使用的值相同.或者,您可以使用 cURL.

To create a POST request, open a up a TCP connection to the host using fsockopen(), then use fwrite() on the handler returned from fsockopen() with the same values you used in the header functions in the OP. Alternatively, you can use cURL.

这篇关于如何使用 PHP header() 函数发布到页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆