php - 从 file_get_contents 获取 POST 数据

标签 php file-get-contents php-5.3

我关注了this post看看如何将数据传递给php的file_get_contents函数,但我似乎无法使用以下方式取回数据:

$data = $_POST['my_param']; // Where my_param is the name of the parameter passed

有人知道如何取回我使用 file_get_contents 调用的脚本中发送到 file_get_contents 的参数值吗?

提前致谢

最佳答案

有示例@php.net http://php.net/manual/en/function.file-get-contents.php#102575

代码:

<?php
/**
make an http POST request and return the response content and headers
@param string $url    url of the requested script
@param array $data    hash array of request variables
@return returns a hash array with response content and headers in the following form:
    array ('content'=>'<html></html>'
        , 'headers'=>array ('HTTP/1.1 200 OK', 'Connection: close', ...)
        )
*/
function http_post ($url, $data)
{
    $data_url = http_build_query ($data);
    $data_len = strlen ($data_url);

    return array ('content'=>file_get_contents ($url, false, stream_context_create (array ('http'=>array ('method'=>'POST'
            , 'header'=>"Connection: close\r\nContent-Length: $data_len\r\n"
            , 'content'=>$data_url
            ))))
        , 'headers'=>$http_response_header
        );
}
?>

但在实际应用中我不会使用这种方法。我建议您改用curl。

curl 的简单示例:

<?php
  $ch = curl_init(); // create curl handle

  $url = "http://www.google.com";
  /**
   * For https, there are more options that you must define, these you can get from php.net 
   */
  curl_setopt($ch,CURLOPT_URL,$url);
  curl_setopt($ch,CURLOPT_POST, true);
  curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query(['array_of_your_post_data']));
  curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3); //timeout in seconds
  curl_setopt($ch,CURLOPT_TIMEOUT, 20); // same for here. Timeout in seconds.
  $response = curl_exec($ch);

  curl_close ($ch); //close curl handle

  echo $response;
?>

使用curl,你可以100%从$_POST获取post参数。 我已经在数十个项目中使用了curl,以前从未让我失望过。

关于php - 从 file_get_contents 获取 POST 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25753586/

相关文章:

node.js - 等效于 Node.JS 的 file_get_contents()

php - Http 400 错误请求 - 波斯语 URL 中的 Php file_get_contents

php - 如何仅使用 DOMXPATH 删除样式属性?

php - 如何验证上传的文件是视频?

php-5.3 - 是否有任何编译器/解释器来执行 php 5.3 的代码?

php - 下拉菜单和数据库

php - 如何在 php mysql 中更新嵌套记录集上的多条记录?

php - 我如何使用 PHP 下载以某种奇怪的方式重定向的 XML 文件?

php - 错误设置证书验证位置 : CAfile ca-bundle. crt CApath:无

php - 透视 mysql 结果集并创建 html 表/矩阵