在PHP中处理携带Cookie或自定义Header的复杂跨域请求,核心是正确配置响应头并配合前端设置。后端需返回 Access-Control-Allow-Origin、Access-Control-Allow-Credentials 等关键头部,且源不能为通配符 *;前端则需在XHR或Fetch请求中显式开启 withCredentials 属性。

跨域预检与凭证传递机制
浏览器对非简单请求(如包含自定义Header或特定Content-Type)会先发送 OPTIONS 预检请求。若涉及Cookie或认证信息,必须确保服务端允许凭证传递,否则浏览器将拦截后续实际请求。

当请求携带Cookie时,服务端响应的 Access-Control-Allow-Origin 必须指定具体域名,不可使用 *。同时需设置 Access-Control-Allow-Credentials: true。预检请求中,浏览器会检查 Access-Control-Allow-Headers 是否包含自定义Header名称,以及 Access-Control-Allow-Methods 是否允许实际请求方法。若任一条件不满足,预检失败,主请求不会发出。
PHP实现带凭证的CORS响应
以下代码展示了如何在PHP脚本中完整配置跨域响应头,支持携带Cookie和自定义Header的请求。将该逻辑置于入口文件或中间件中即可生效。

<?php
// CORS Configuration for PHP with Credentials
$allowed_origins = ['https://frontend.example.com', 'https://app.example.com'];
$request_origin = $_SERVER['HTTP_ORIGIN'] ?? '';
// Check if the request origin is in the allowed list
if (in_array($request_origin, $allowed_origins)) {
// Set the specific origin to allow credentials
header('Access-Control-Allow-Origin: ' . $request_origin);
// Allow credentials (cookies, authorization headers, etc.)
header('Access-Control-Allow-Credentials: true');
// Define allowed headers for preflight and actual requests
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Custom-Header');
// Define allowed methods
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
// Handle preflight request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(204); // No Content
exit;
}
} else {
// Optional: Return 403 if origin is not allowed
http_response_code(403);
echo json_encode(['error' => 'Origin not allowed']);
exit;
}
// Your main application logic here
echo json_encode(['status' => 'success', 'message' => 'Request processed']);
运行此脚本时,若请求来自白名单内的域名且携带Cookie,浏览器将成功接收响应。若前端未设置 withCredentials,即使后端配置正确,Cookie也不会随请求发送。若自定义Header未在 Allow-Headers 中声明,预检请求将返回403,导致业务请求无法执行。调试时可打开浏览器开发者工具的Network面板,观察Preflight Request的状态及响应头内容。
该实现针对动态源进行校验,避免硬编码带来的安全风险。通过读取请求中的 Origin 头并与白名单比对,决定放行范围。同时明确列出允许的Header和方法,确保预检通过。
前端withCredentials配置要求
即使后端配置正确,前端若未启用凭证传递,浏览器仍会拒绝发送Cookie。必须在发起请求的代码中显式设置 withCredentials 为 true。
对于Fetch API,需在初始化选项中添加 credentials: 'include'。对于XMLHttpRequest,则设置 xhr.withCredentials = true。注意:一旦启用此选项,后端响应的 Access-Control-Allow-Origin 绝不能是 *,否则浏览器会因安全策略拒绝接收响应体。自定义Header在预检阶段必须被服务端明确声明允许,否则实际请求会被浏览器直接拦截,不会发送到服务器。