如何使用 file_get_contents 在 PHP 中发布数据? [英] How to post data in PHP using file_get_contents?
问题描述
我使用 PHP 的函数 file_get_contents()
来获取 URL 的内容,然后我通过变量 $http_response_header
处理标头.
I'm using PHP's function file_get_contents()
to fetch contents of a URL and then I process headers through the variable $http_response_header
.
现在的问题是,有些 URL 需要将一些数据发布到 URL(例如,登录页面).
Now the problem is that some of the URLs need some data to be posted to the URL (for example, login pages).
我该怎么做?
我意识到使用 stream_context 我也许能够做到这一点,但我并不完全清楚.
I realize using stream_context I may be able to do that but I am not entirely clear.
谢谢.
推荐答案
使用 file_get_contents 发送 HTTP POST 请求
并不难,实际上:正如您所猜测的,您必须使用 $context
参数.
PHP 手册中给出了一个示例,在此页面上:HTTP 上下文选项 (引用) :
$postdata = http_build_query(
array(
'var1' => 'some content',
'var2' => 'doh'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/submit.php', false, $context);
基本上,您必须创建一个流,使用正确的选项(该页面上有完整列表),并将其用作 file_get_contents
的第三个参数-- 仅此而已 ;-)
Basically, you have to create a stream, with the right options (there is a full list on that page), and use it as the third parameter to file_get_contents
-- nothing more ;-)
作为旁注:一般来说,要发送 HTTP POST 请求,我们倾向于使用 curl,它提供了很多选项——但流是 PHP 的优点之一,没人知道......太糟糕了..
As a sidenote : generally speaking, to send HTTP POST requests, we tend to use curl, which provides a lot of options an all -- but streams are one of the nice things of PHP that nobody knows about... too bad...
这篇关于如何使用 file_get_contents 在 PHP 中发布数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!