【问题标题】:How to post data in PHP using file_get_contents?如何使用 file_get_contents 在 PHP 中发布数据?
【发布时间】:2011-01-27 13:35:15
【问题描述】:

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

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

我该怎么做?

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

谢谢。

【问题讨论】:

标签: php http http-post file-get-contents


【解决方案1】:

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


PHP手册中有一个例子,在这个页面:HTTP context options (quoting) :

$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 的优点之一,没有人知道......太糟糕了...... .

【讨论】:

  • 谢谢。我猜如果我需要将相同的 POST 参数传递给请求的页面,我可以将 $_POST 中的内容插入到 $postdata 中?
  • 我想你可以做这样的事情;但content 不能是 PHP 数组:它必须是查询字符串 (即它必须具有这种格式:param1=value1&param2=value2&param3=value3 ;;这意味着您可能必须使用http_build_query($_POST)
  • 太棒了!我正在寻找一种将 POST 数据传递到另一个页面的方法,这可以通过 $postdata = http_build_query($_POST) 来实现。
  • 有趣的是,这对我来说根本不起作用我已经尝试了几个小时,我所有的请求都变成了获取查询
  • 要发送多个标头值,请将它们全部放入一个带有\r\n 换行符的字符串中 - 请参阅:stackoverflow.com/a/2107792/404960
【解决方案2】:

另一种选择,您也可以使用 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");
}

【讨论】:

  • 出于某种原因,这对我有用,但 PHP 官方示例没有。 +1 toto=1&tata=2 也是如此。但是,我没有使用fopen
  • @Ġiĺàɗ 我们在这里不称人们为“菜鸟”。这是一个友好的警告。
【解决方案3】:
$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");
}

【讨论】:

  • 请尝试提供详细的答案,而不是简单地复制/粘贴代码。
  • 这也是不必要的复杂。您可以使用file_get_contents 代替fopen + stream_get_contents。你甚至没有关闭“文件”。请参阅@PascalMARTIN 接受的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-07
  • 2012-07-04
  • 2018-03-29
  • 2012-06-20
相关资源
最近更新 更多