PHP调用API最稳妥方式是cURL:需设超时、SSL验证和错误检查;GET请求要CURLOPT_RETURNTRANSFER=true,POST传JSON需json_encode+Content-Type头;SSL错误应配CA证书而非禁用验证。

PHP 调用 API 接口最稳妥的方式是用 curl,而不是 file_get_contents 或 stream_context_create —— 后两者在 HTTPS、超时、错误处理上容易出问题。
用 curl 发送 GET 请求并处理 JSON 响应
这是最常见场景:请求第三方 API(如天气、短链、支付回调验证),拿到 JSON 数据后 json_decode 解析。
关键点在于显式设置超时、SSL 验证和错误检查:
-
curl_setopt($ch, CURLOPT_TIMEOUT, 10)必须设,否则默认永不超时,可能卡死进程 -
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true)必须设,否则直接输出而非返回字符串 -
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false)仅开发调试时临时关闭;生产环境必须保持true并确保系统有 CA 证书(如 CentOS 的/etc/pki/tls/certs/ca-bundle.crt) - 调用后务必检查
curl_error($ch)和 HTTP 状态码,200不等于业务成功,API 可能返回{"code":401,"msg":"token expired"}
```php
$ch = curl_init('https://api.example.com/v1/user?id=123');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); // 生产环境不要关
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
<p>if ($error || $httpCode !== 200) {
throw new Exception("API request failed: {$error}, HTTP {$httpCode}");
}
$data = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception('Invalid JSON response');
}</p><pre class='brush:</pre>;toolbar:false;'>
<H3>用 <code>curl</code> 发送 POST 请求(JSON 格式)</H3>
<p>向 RESTful API 提交数据时,多数要求 <code>Content-Type: application/json</code>,且请求体是原始 JSON 字符串,不是 <code>application/x-www-form-urlencoded</code>。</p>
<p>常见错误是误用 <code>curl_setopt($ch, CURLOPT_POSTFIELDS, $arr)</code> 直接传数组 —— 这会自动变成表单编码,服务端收不到 <code>json_decode(file_get_contents('php://input'))</code>。</p>
<ul>
<li>先用 <code>json_encode($data)</code> 序列化数组为字符串</li>
<li>手动设置 <code>Content-Type</code> header:<code>curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json'])</code></li>
<li><code>curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonString)</code> 传字符串,不是数组</li>
<li>如果 API 要求带 token,加到 header:<code>['Authorization: Bearer abc123', 'Content-Type: application/json']</code></li>
</ul>
<pre>```php
$data = ['name' => 'Alice', 'email' => 'a@example.com'];
$jsonString = json_encode($data);
$ch = curl_init('https://api.example.com/v1/users');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonString);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$response = curl_exec($ch);
curl_close($ch);
```</pre>
<H3>遇到 <code>cURL error 60</code> 或 <code>SSL certificate problem</code> 怎么办</H3>
<p>这是 Windows 或旧版 PHP(尤其 WAMP/XAMPP)常见问题,本质是 cURL 找不到 CA 证书路径。</p>
<ul>
<li>先确认是否真要绕过 SSL:<code>curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false)</code> 是临时方案,不能上线</li>
<li>正确做法是下载最新 CA 包(如 <a href="https://curl.se/ca/cacert.pem">https://curl.se/ca/cacert.pem</a>),保存为 <code>cacert.pem</code></li>
<li>在 php.ini 中设置:<code>curl.cainfo = "/path/to/cacert.pem"</code>(Windows 用反斜杠或双正斜杠)</li>
<li>或运行时指定:<code>curl_setopt($ch, CURLOPT_CAINFO, '/var/www/cacert.pem')</code></li>
<li>Linux 系统通常已内置,但 Docker 容器里可能缺失,需在镜像中 <code>apt-get install ca-certificates</code></li>
</ul>
<p>别只盯着“能跑通”,API 调用的健壮性藏在超时控制、SSL 验证、HTTP 状态码判断、JSON 解析容错这些细节里。漏掉任意一项,上线后都可能变成深夜告警。











