加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > PHP > 正文

php file_get_contents模拟post提交数据

发布时间:2020-05-25 02:32:58 所属栏目:PHP 来源:互联网
导读:本文章向大家介绍php file_get_contents模拟post提交数据,需要的朋友可以参考一下。

需求

我正在使用PHP的函数file_get_contents()来获取URL的内容,然后我通过变量处理头文件$http_response_header。

现在问题是某些URL需要将一些数据发布到URL(例如,登录页面)。

我怎么做?

我意识到使用stream_context我可以做到这一点,但我并不完全清楚。

实现方法:

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

PHP手册中给出了一个示例:

$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- 仅此而已;-)

作为旁注:一般来说,为了发送HTTP POST请求,我们倾向于使用curl,它提供了很多选项。

另一种方法,你也可以使用fopen

$params = array('http' => array(

'method' => 'POST',

'content' => 'toto=1&tata=2'

));

$ctx = stream_context_create($params);

$fp = @fopen($sUrl,'rb',$ctx);

if (!$fp)

{

throw new Exception("Problem with $sUrl,$php_errormsg");

}

$response = @stream_get_contents($fp);

if ($response === false)

{

throw new Exception("Problem reading data from $sUrl,$php_errormsg");

}

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读