带重试与超时的 HTTP 请求
封装 curl,设置连接与总超时、失败重试、GET/POST 统一入口、错误信息可读。
更新于 2026-11-0739 行代码
完整代码
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];
}
怎么用
- $r = http('https://api.example.com/user', ['id' => 1]);
- 判断 $r['ok'],取 $r['body'],失败时把 $r['error'] 写日志。
- 需要 JSON 请求体时传字符串,并加 Content-Type: application/json。
注意
- 只对 5xx 和网络错误重试,4xx 重试没有意义。
- 重试要退避(usleep),否则会把对方打得更惨。
- 生产环境不建议 FOLLOWLOCATION,跳转到内网地址可能造成 SSRF。