【问题标题】:Get POST data from file_get_contents从 file_get_contents 获取 POST 数据
【发布时间】:2014-09-09 21:06:25
【问题描述】:

我关注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 的参数值吗?

提前致谢

【问题讨论】:

  • @dandavis 除非你把 method = "POST" 放在上下文对象中。
  • 您的问题不清楚。您是在询问如何访问您使用file_get_contents 调用的脚本中的参数,还是在包含file_get_contents 的脚本中访问参数?
  • @dandavis 我确实发布了 POST,但仍然没有工作
  • @Barmar 在我用 file_get_contents 调用的脚本中
  • 然后$_POST['my_param'] 应该可以工作。请发布调用者脚本。

标签: php file-get-contents php-5.3


【解决方案1】:

有例子@php.nethttp://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 获取您的帖子参数。 我在几十个项目中使用过 curl,从来没有让我失望过。

【讨论】:

  • 第一个示例与他们在我遵循的帖子中所做的完全相同(包装在一个函数中),并且 curl 不适合我
  • 您可以尝试调试发送的标头。查看您的帖子标题是否实际发送。如果它们被发送,然后尝试调查,为什么服务器不接受它们。
猜你喜欢
  • 2016-10-27
  • 2020-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-13
  • 2015-10-22
  • 1970-01-01
相关资源
最近更新 更多