详述file_get_contents、getimagesize严重耗时问题

wufei123 发布于 2023-04-29 阅读(1535)

file_get_contents、getimagesize严重耗时问题

1、场景及问题描述

第三方首次登录(QQ、微信)时,自动将平台用户头像更换为第三方头像,相关代码如下

1

详述file_get_contents、getimagesize严重耗时问题

2

3

4

5

6

7

8

9

10

11

12

$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秒

后来在网上查找一番说可以设置超时

1

2

3

4

5

6

7

$context = stream_context_create([

    'http' => [

        'timeout' => 3 //超时时间,单位为秒

    ]

]); 

// Fetch the URL's contents

$fileContent = file_get_contents($logo, 0, $context);

然而并没有用,3秒超时没有生效

2、解决办法

更换使用 GuzzleHttp或者PHP自己的curl获取头像内容,结果没有超时

1

2

3

4

5

6

7

8

9

10

11

12

13

$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

1

2

3

4

5

6

7

8

9

10

11

12

13

$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);

自此问题解决。


以上就是详述file_get_contents、getimagesize严重耗时问题的详细内容


标签:  PHP 免费教程 

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

河南中青旅行社综合资讯 奇遇综合资讯 盛世蓟州综合资讯 综合资讯 游戏百科综合资讯 新闻74765