如何使用file_get_contents在PHP中发布数据?

Par*_*pra 287 php http http-post file-get-contents

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

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

我怎么做?

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

谢谢.

Pas*_*TIN 574

使用发送HTTP POST请求file_get_contents并不难,实际上:正如您猜测的那样,您必须使用该$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);
Run Code Online (Sandbox Code Playgroud)

基本上,你必须使用正确的选项创建一个流(该页面上有一个完整的列表),并将其用作第三个参数file_get_contents- 仅此而已;-)


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

  • 我想你可以做那样的事情; 但是`content`必须不是PHP数组:它必须是一个查询字符串*(即它必须具有以下格式:`param1 = value1&param2 = value2&param3 = value3`)*;; 这意味着你可能不得不使用`http_build_query($ _ POST)` (6认同)
  • 精彩!我正在寻找一种方法将POST数据传递到另一个页面,这可以通过`$ postdata = http_build_query($ _ POST)`来实现. (2认同)

Mac*_*ric 20

另一种方法,你也可以使用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");
}
Run Code Online (Sandbox Code Playgroud)

  • @Ġiĺàɗ我们这里不叫人'noob'.这是对这种情况的友好警告. (4认同)