从file_get_contents获取POST数据

时间:2014-09-09 21:06:25

标签: 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的参数值吗?

提前致谢

1 个答案:

答案 0 :(得分:2)

有例子@ 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获得你的帖子参数。 我在几十个项目中使用过卷曲,以前从未失败过。