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

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

我怎么做呢?

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

谢谢。


实际上,使用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的第三个参数——没有别的;-)

附注:一般来说,要发送HTTP POST请求,我们倾向于使用curl,它提供了很多选项——但流是PHP的一个好东西,没有人知道…太糟糕了……

另外,你也可以使用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");
}
$sUrl = 'http://www.linktopage.com/login/';
$params = array('http' => array(
    'method'  => 'POST',
    'content' => 'username=admin195&password=d123456789'
));

$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");
}