如何使用file_get_contents在PHP中发布数据? [英] How to post data in PHP using file_get_contents?

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

问题描述

我正在使用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.

谢谢。

推荐答案

发送HTTP POST使用 file_get_contents 的请求并不难,实际上:正如你猜测的那样,你必须使用 $ context 参数。

Sending an HTTP POST request using file_get_contents is not that hard, actually : as you guessed, you have to use the $context parameter.



有一个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屋!

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