普通网友 2016-04-21 12:42
浏览 40
已采纳

file_get_contents返回内容中的HTTP标头

I am using file_get_contents() to perform a POST to an API service. This is working for most of the queries. However, recently I had a failure in which file_get_contents() returned HTTP headers in the content!

For the code:

$resp = file_get_contents("http://10.72.18.21:8000",false, $context);
var_dump($resp);
var_dump($http_response_header);

I get the following content and headers every time:

string(114328) "Server: Spark Proxy Server
Content-Length: 114272

{"records":....}
"
array(1) {
  [0]=>
  string(31) "HTTP/1.0 200 Spark Proxy Server"
}

Notice that inside the $resp you can see headers (the first two lines) which should normally be parsed in $http_response_header.

I have also tried two different approaches to do the POST: (a) fopen + while loop and (b) fopen + stream_get_contents. In all three cases the results are the same. The common thing between all three is the stream context which I create using:

$opts = array('http' =>
array(
    'method'  => 'POST',
    'header'  => 'Content-type: application/x-www-form-urlencoded;charset=utf-8',
    'content' => http_build_query($params)
    )
);

$context  = stream_context_create($opts);

Now, querying the same API with the same code but with a single parameter modified, everything works as expected and the complete headers are:

array(3) {
  [0]=>
  string(31) "HTTP/1.0 200 Spark Proxy Server"
  [1]=>
  string(26) "Server: Spark Proxy Server"
  [2]=>
  string(19) "Content-Length: 288"
}

Finally, I have tried the same call that fails with python and cUrl and in both cases the results are correct, so I am pretty sure it is php related issue.

Questions:

  • Has anyone seen this behavior before?
  • Is there a way to perform the same POST without using stream_context_create?
  • Can it be time related? The example that fails takes up to 1.4 minutes to complete
  • 写回答

1条回答 默认 最新

  • duancai1904 2016-04-22 11:46
    关注

    I have tried this again today... and instead of headers mixed in the content, I got empty content and partial headers. This error though is a lot easier to google and lead me to this SO answer talking about a similar problem (weird file_get_contents behavior).

    As the first comment hinted, changing the default socket timeout solves my problem (it was set to 60):

    ini_set("default_socket_timeout", 600);
    

    I am not quite sure how the socket can timeout since the data and the headers received seemed complete...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP