PHP cURL如何正确返回第三方服务的application/pdf响应给调用方
解决PHP转发PDF响应时Content-Type错误的问题
方案1:硬编码Content-Type(快速适配PDF场景)
直接在输出响应体前,通过PHP的header()函数指定正确的MIME类型,覆盖默认的text/html:
$url = 'https://localhost:7174/customers/123/pdf'; $expectedMimeType = 'application/pdf'; $token = '****************************************'; // 优先发送正确的Content-Type响应头 header('Content-Type: ' . $expectedMimeType); $curl = curl_init(); curl_setopt_array( $curl, array( CURLOPT_URL => $url, CURLOPT_HTTPHEADER => array( 'Authorization: Bearer '.$token, 'Accept: '.$expectedMimeType ) ) ); curl_exec($curl); curl_close($curl); exit();
方案2:自动传递第三方服务的响应头(通用适配所有MIME类型)
如果需要后续适配其他类型的响应(如图片、Excel等),可以获取第三方服务返回的完整响应头,提取并转发给客户端:
$url = 'https://localhost:7174/customers/123/pdf'; $expectedMimeType = 'application/pdf'; $token = '****************************************'; $curl = curl_init(); curl_setopt_array( $curl, array( CURLOPT_URL => $url, CURLOPT_HTTPHEADER => array( 'Authorization: Bearer '.$token, 'Accept: '.$expectedMimeType ), CURLOPT_HEADER => true, // 让curl返回响应头+响应体内容 CURLOPT_RETURNTRANSFER => true // 将响应转为字符串,方便拆分处理 ) ); $fullResponse = curl_exec($curl); $headerLength = curl_getinfo($curl, CURLINFO_HEADER_SIZE); // 拆分响应头和响应体 $responseHeaders = substr($fullResponse, 0, $headerLength); $responseBody = substr($fullResponse, $headerLength); // 遍历并转发关键响应头 foreach (explode("\r\n", $responseHeaders) as $headerLine) { $headerLine = trim($headerLine); if (empty($headerLine)) continue; // 转发Content-Type if (stripos($headerLine, 'Content-Type:') === 0) { header($headerLine); } // 可选:转发下载相关的Content-Disposition头 if (stripos($headerLine, 'Content-Disposition:') === 0) { header($headerLine); } } // 输出响应体内容 echo $responseBody; curl_close($curl); exit();
关键注意点
- 调用
header()函数前,确保没有任何输出(包括代码开头的空格、换行符),否则会导致头设置失效。 - 方案2可以自动适配第三方服务返回的任何MIME类型,无需修改代码即可支持新的响应格式。
内容的提问来源于stack exchange,提问作者PaulH567
相关产品推荐
相关产品推荐

