写给愿意动手的 PHP 开发者
PHP学习网 PHP学习网
公告PHP学习网为公益性网站,致力于为广大PHP爱好者服务
首页/ PHP 源码/ 带重试与超时的 HTTP 请求
网络与接口 通用 PHP 7.4+

带重试与超时的 HTTP 请求

封装 curl,设置连接与总超时、失败重试、GET/POST 统一入口、错误信息可读。

完整代码

PHP
<?php
function http(string $url, array $data = null, array $headers = [], int $retry = 2): array
{
    $attempt = 0;
    do {
        $ch = curl_init($url);
        $opt = [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CONNECTTIMEOUT => 3,
            CURLOPT_TIMEOUT        => 10,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_MAXREDIRS      => 3,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_USERAGENT      => 'PHPStudy/1.0',
        ];
        if ($data !== null) {
            $opt[CURLOPT_POST] = true;
            $opt[CURLOPT_POSTFIELDS] = is_array($data) ? http_build_query($data) : $data;
        }
        if ($headers) {
            $opt[CURLOPT_HTTPHEADER] = $headers;
        }
        curl_setopt_array($ch, $opt);

        $body = curl_exec($ch);
        $errno = curl_errno($ch);
        $error = curl_error($ch);
        $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($errno === 0 && $code < 500) {
            return ['ok' => $code >= 200 && $code < 400, 'code' => $code, 'body' => $body, 'error' => ''];
        }
        $attempt++;
        usleep(200000 * $attempt);
    } while ($attempt <= $retry);

    return ['ok' => false, 'code' => $code ?? 0, 'body' => '', 'error' => $error ?: 'HTTP ' . $code];
}

怎么用

  1. $r = http('https://api.example.com/user', ['id' => 1]);
  2. 判断 $r['ok'],取 $r['body'],失败时把 $r['error'] 写日志。
  3. 需要 JSON 请求体时传字符串,并加 Content-Type: application/json。

注意

  • 只对 5xx 和网络错误重试,4xx 重试没有意义。
  • 重试要退避(usleep),否则会把对方打得更惨。
  • 生产环境不建议 FOLLOWLOCATION,跳转到内网地址可能造成 SSRF。

相关源码