原因:
PHP的file_get_contents函数可能出现读取远程图片耗时很久的问题,排除远程服务器响应慢的问题,这是因为file_get_contents无法智能判断图片数据是否读取完并关闭连接,所以一直在等待,直到超时时间达到默认的default_socket_timeout才会断开连接。
解决方法:
1、动态设置默认的连接超时时间:
ini_set('default_socket_timeout', 5);//设置默认超时时间为5秒
file_get_contents($url);
2、使用CURL:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
3、使用GuzzleHttp:
$client = new \GuzzleHttp\Client();
$response = $client->get($url);
$content = $response->getBody()->getContents();
以上三种方法,推荐方法2和方法3!