file_get_contents 比 浏览器慢 ?

你说的没有错误,file_get_contents在多次访问同一url时,会出现偶尔慢,甚至无响应等情况。

之前也一直没有搞清楚具体原因,通过浏览器发现一点也不慢,就没管,后来有次无意间读php源码,发现file_get_contents在发起请求时并不会发送"connection" HTTP头!!!

若果不发送"connection" HTTP头,目标服务器会认为tcp请求还处在keep-alive,因此不会close,那么什时候才能close呢,这就得看目标网站的服务器配置了,有的是几秒有的可能更慢。

可以通过wireshark抓包就能看到,用curl的话,目标网站会close tcp connection,而用file_get_contents时则不会。

有一种解决方案,在使用时加上所需要的header,你可以试试,希望对你有帮助。


$context = stream_context_create(array('http' => array('header'=>'Connection: close\r\n')));
file_get_contents("$your_url", false, $context);

 

出处:http://bbs.csdn.net/topics/391833478?page=1

posted @ 2016-11-21 12:01  stma  阅读(400)  评论(0)    收藏  举报