file_get_contents、getimagesize严重耗时问题
file_get_contents、getimagesize 严重耗时问题#
1、场景及问题描述#
第三方首次登录(QQ、微信)时,自动将平台用户头像更换为第三方头像,相关代码如下
$logo = "http://thirdqq.qlogo.cn/g?b=oidb&k=OMu7e7tukTueShatFXVX1w&kti=ZDyqNAAAAAE&s=100&t=1611112388"
try {
$fileContent = file_get_contents($logo);
} catch (\Exception $e) {
throw new \Exception("读取文件[" . $logo ."]失败");
}
$imageInfo = getimagesize($logo);
if (empty($imageInfo)) {
throw new \Exception("文件[" . $logo ."]格式有误(非图片)");
}
$base64Image = 'data:' . $imageInfo['mime'] . ';base64,' . base64_encode($fileContent);
结果在获取到 QQ 用户头像,用 file_get_contents () 获取头像文件内容时,耗时 18 到 20 秒
后来在网上查找一番说可以设置超时
$context = stream_context_create([
'http' => [
'timeout' => 3 //超时时间,单位为秒
]
]);
// Fetch the URL's contents
$fileContent = file_get_contents($logo, 0, $context);
然而并没有用,3 秒超时没有生效
2、解决办法#
更换使用 GuzzleHttp 或者 PHP 自己的 curl 获取头像内容,结果没有超时
$logo = "http://thirdqq.qlogo.cn/g?b=oidb&k=OMu7e7tukTueShatFXVX1w&kti=ZDyqNAAAAAE&s=100&t=1611112388"
try {
$client = new Client(['timeout' => 3]);
$fileContent = $client->get($logo)->getBody()->getContents();
} catch (\Exception $e) {
throw new \Exception("读取文件[" . $logo ."]失败");
}
$imageInfo = getimagesize($logo);
if (empty($imageInfo)) {
throw new \Exception("文件[" . $logo ."]格式有误(非图片)");
}
$base64Image = 'data:' . $imageInfo['mime'] . ';base64,' . base64_encode($fileContent);
但是呢,有一个耗时的发现来了,getimagesize 函数耗时也是 18 到 20 秒
头像内容已经正常获取到了,PHP 还有一个通过图片内容获取 mime 的函数,即 getimagesizefromstring
$logo = "http://thirdqq.qlogo.cn/g?b=oidb&k=OMu7e7tukTueShatFXVX1w&kti=ZDyqNAAAAAE&s=100&t=1611112388"
try {
$client = new Client(['timeout' => 3]);
$fileContent = $client->get($logo)->getBody()->getContents();
} catch (\Exception $e) {
throw new \Exception("读取文件[" . $logo ."]失败");
}
$imageInfo = getimagesizefromstring($logo);
if (empty($imageInfo)) {
throw new \Exception("文件[" . $logo ."]格式有误(非图片)");
}
$base64Image = 'data:' . $imageInfo['mime'] . ';base64,' . base64_encode($fileContent);
自此问题解决
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: