php file_get_contents模拟post提交数据

时间:2017-07-28
本文章向大家介绍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', false, $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");
}