用 curl 替换 file_get_contents

初学 PHP 时喜欢使用 file_get_contents 来访问 URL,对于量小来说是没有问题的。但是一次游戏刚上线就被运营方提示说用户充值总是失败,返回十分缓慢,问题定位了许久才发现是 file_get_contents 返回过慢导致的,改用 curl 就好了。因而,在所有重要的场景中都直接使用 cURL 方法;

如果需要打开 file_get_contents 方法需要在 php.ini 中设置 allow_url_fopen=On 否则将会阻塞页面; 另外 file_get_contents 是不缓存 DNS 查询的,每次调用都会查询 DNS;效率上 cURL 远胜过 file_get_contents

用法:

1
2
3
4
5
6
7
8
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_HEADER, 0);
$output = curl_exec($ch);
curl_close($ch);
return $output;