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

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

问题描述

我在这里找到了以下代码,我认为它做了什么我想,但它不起作用:

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

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

我希望发布表单数据,而不必将用户发送到中间页面,然后使用JavaScript重定向他们。我也不想使用GET,因此使用后退按钮并不容易。



这段代码有什么问题吗?还是有更好的方法?



编辑我在考虑头文件函数的功能。我想我可以让浏览器将数据发送回服务器,但这不是它的目的。相反,我在我的代码中找到了一种避免需要发布帖子的方法(不会中断并继续转到交换机中的下一个案例)。

解决方法

头文件函数用于发送HTTP响应头文件给用户(即不能用它来创建请求头文件。)

可能我问你为什么要这样做?为什么模拟一个POST请求,当你可以在那里,然后对数据采取行动?我假设script.php当然驻留在你的服务器上。



要创建一个POST请求,使用fsockopen()打开一个与主机的TCP连接,然后在fsockopen()返回的处理函数上使用fwrite(),其值与您在OP。或者,您可以使用cURL。


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\r\n");
header("Host: $host\r\n");
header("Content-type: application/x-www-form-urlencoded\r\n");
header("Content-length: " . strlen($data) . "\r\n");
header("Connection: close\r\n\r\n");
header($data);

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).

解决方案

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

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.

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()函数向页面发布POST?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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