汉字魔法师
118.67M · 2026-02-04
在 Web 开发中,PHP 脚本可以扮演两种角色:
| 角色 | 行为 | 使用工具 |
|---|---|---|
| 客户端(Client) | 主动调用其他服务器(如微信 API、支付接口) | cURL |
| 服务器(Server) | 响应浏览器或前端 AJAX 请求 | header() |
所以:
cURLheader()cURL:PHP 作为“客户端”发请求$data = ['user_id' => 123, 'action' => 'login'];
$json = json_encode($data);
$ch = curl_init(); //初始化
curl_setopt_array($ch, [
CURLOPT_URL => 'https://api.example.com/notify', //设置路径
CURLOPT_POST => true, //是否为post
CURLOPT_POSTFIELDS => $json, //post的数据
CURLOPT_RETURNTRANSFER => true, //是否转成字符串
CURLOPT_HTTPHEADER => [ //header请求头
'Content-Type: application/json', // 告诉对方:“我发的是 JSON”
'Authorization: Bearer your_token'
]
]);
$response = curl_exec($ch); //执行
curl_close($ch); //关闭
CURLOPT_HTTPHEADER 设置的是 请求头(Request Headers)'Content-Type: application/json',否则对方可能无法解析cURL 的 Header 是 你告诉“目标服务器” 的话header():PHP 作为“服务器”响应浏览器header('Content-Type: application/json; charset=utf-8');
echo json_encode(['status' => 'success']);
header('Location: /dashboard.php');
exit; // ️ 必须加 exit!
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="report.pdf"');
readfile('report.pdf');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
header() 设置的是 响应头(Response Headers)header() 的 Header 是 你告诉“浏览器/前端” 的话| 项目 | cURL | header() |
|---|---|---|
| 角色 | 客户端(主动请求别人) | 服务器(被动响应浏览器) |
| 方向 | PHP → 外部服务器 | PHP → 浏览器/前端 |
| Header 类型 | 请求头(Request Header) | 响应头(Response Header) |
| 典型用途 | 调 API、发数据 | 返回 JSON、跳转、下载、设 Cookie |
| 是否需提前输出 | 无限制 | 必须在任何输出前调用 |
| 常见 Header | Content-Type, Authorization | Content-Type, Location, Cache-Control |
Content-Type 两边都能用?是的!但含义不同:
cURL 中: “我发的数据是 JSON”header() 中: “我返回的数据是 JSON”当然可以!只要:
header('Content-Type: text/html').text() 而不是 .json() 读取 查 MDN:Common MIME types
或用浏览器 DevTools 看别人网站的响应头。
header() 报错 “Cannot modify header information”? 因为前面已经有输出(空格、echo、BOM 等)。
解决方案:
header() 在最顶部ob_start();F12 → Network → 点请求 → 查看 Response Headers