When a third party logs in for the first time (QQ, WeChat), the platform user’s avatar is automatically Change to a third-party avatar, the relevant code is as follows
$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);
The result is that when obtaining the QQ user avatar and using file_get_contents() to obtain the avatar file content, it takes 18 to 20 seconds
Find it later on the Internet It was said that you can set a timeout
$context = stream_context_create([ 'http' => [ 'timeout' => 3 //超时时间,单位为秒 ] ]); // Fetch the URL's contents $fileContent = file_get_contents($logo, 0, $context);
However, it is useless. The 3-second timeout does not take effect
Replace using GuzzleHttp or PHP's own curl to obtain the avatar content , the result did not time out
$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);
However, there is a time-consuming discovery, the getimagesize function also takes 18 to 20 seconds
The avatar content has been obtained normally, and there is another pass through PHP The function to obtain mime for image content is 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);
. This problem has been solved.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of Detailed description of the serious time-consuming problem of file_get_contents and getimagesize. For more information, please follow other related articles on the PHP Chinese website!