详述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);

自此问题解决。

推荐学习:《PHP视频教程》

以上就是详述file_get_contents、getimagesize严重耗时问题的详细内容,更多请关注https://www.sxiaw.com/其它相关文章!