首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 實現跨域請求 (CORS) 完整指南:Access-Control-Allow-Origin 配置與預檢請求處理

     編輯:PHP 綜合知識

跨域問題由來

瀏覽器同源策略攔截非同源請求。本地文件 (file:// 或 localhost:8080) 請求 API (api.example.com) 觸發 CORS 錯誤:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

預檢請求 (Preflight)

非簡單請求 (含自定義 Header、非 GET/POST/HEAD、Content-Type 非表單類型) 會先發送 OPTIONS 請求詢問服務器是否允許跨域。

服務器端解決方案 (PHP)

核心代碼

<?php
// 必須在任何輸出前設置
header('Access-Control-Allow-Origin: *'); // 或具體域名: https://a.example.com
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
header('Access-Control-Max-Age: 86400'); // 預檢緩存 24 小時

// 處理 OPTIONS 預檢請求直接返回
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// 正常業務邏輯...
echo json_encode(['status' => 'ok', 'data' => [...]]);

關鍵 Header 詳解

Header作用示例
Access-Control-Allow-Origin允許的源 (* 或單一域名)* / https://a.com
Access-Control-Allow-Methods允許的 HTTP 方法GET, POST, OPTIONS
Access-Control-Allow-Headers允許的請求頭Content-Type, Authorization
Access-Control-Allow-Credentials是否允許攜帶 Cookietrue (需 Origin 非 *)
Access-Control-Max-Age預檢結果緩存秒數86400
Access-Control-Expose-Headers允許 JS 讀取的響應頭X-Total-Count

帶憑證請求 (Cookies/Authorization)

header('Access-Control-Allow-Origin: https://a.example.com'); // 不能用 *
header('Access-Control-Allow-Credentials: true');

前端 AJAX 設置 xhr.withCredentials = true 或 fetch(..., {credentials: 'include'})。

Nginx/Apache 層面配置 (推薦)

# Nginx
location /api/ {
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
    add_header Access-Control-Allow-Headers 'Content-Type, Authorization';
    if ($request_method = OPTIONS) { return 204; }
    proxy_pass https://php_backend;
}

總結

CORS 核心在服務器響應頭,PHP 中用 header() 設置,必須在輸出前。生產環境建議:具體域名而非 *、配置允許憑證、Nginx 統一處理 避免代碼入侵。理解預檢機制有助於排查疑難跨域問題。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved