需求
我正在使用PHP的函数file_get_contents()来获取URL的内容,然后我通过变量处理头文件$http_response_header。
现在问题是某些URL需要将一些数据发布到URL(例如,登录页面)。
我怎么做?
我意识到使用stream_context我可以做到这一点,但我并不完全清楚。
实现方法:
使用file_get_contents发送HTTP POST请求并不难,实际上:正如您猜测的那样,您必须使用该$context参数。
$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");
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。