我无法让 CORS 接受来自导入的 PHP 脚本的跨源请求。我的网站有两个子域:“php.
我有一个名为“common_headers.php”的文件,用于设置 CORS 标头,我在其他 PHP 脚本中通过“require”导入该文件。在“get_flagges_policies.php”和“validate_session_token.php”中,我在文件的最顶部执行此操作。但是,如果我不导入“validate_session_token”,CORS 仅接受“get_flaged_policies”。
我尝试手动将标头添加到“validate_session_token”,但这并不能解决问题。我目前唯一的解决方案是将用于验证会话令牌的代码粘贴到我标记的策略脚本中,但随后我必须对所有需要验证的 PHP 脚本执行相同的操作。
php.
<?php
function setCommonHeaders() {
$allowedOrigins = [
'https://php.<my website>.com',
'https://admin.<my website>.com',
'https://www.<my website>.com',
];
if (isset($_SERVER['HTTP_ORIGIN'])) {
$origin = $_SERVER['HTTP_ORIGIN'];
$parsedUrl = parse_url($origin);
$host = $parsedUrl['host'] ?? '';
if (in_array($origin, $allowedOrigins) || preg_match('/(^|\.)<my website>\.com$/', $host)) {
header("Access-Control-Allow-Origin: " . $origin);
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
header("Access-Control-Allow-Methods: POST, GET");
header("Access-Control-Max-Age: 3600");
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header("HTTP/1.1 200 OK");
return;
}
}
} else {
header("Content-Type: application/json; charset=UTF-8");
}
}
?>
php.
<?php
require '../miscellaneous/common_headers.php';
setCommonHeaders();
include '../../connect.php';
$input = json_decode(file_get_contents('php://input'), true);
$limit = isset($input['limit']) ? (int) $input['limit'] : 20;
$offset = isset($input['offset']) ? (int) $input['offset'] : 0;
$session_token = $input['session_token'];
require '../session/validate_session_token.php'; // This line is causing the CORS error
validateSessionToken($conn, $session_token, true);
// ... rest of script
php.
<?php
require '../miscellaneous/common_headers.php';
setCommonHeaders();
function validateSessionToken($conn, $session_token, $adminRequired) {
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if (!isset($_SESSION['user_id'])) {
exit('user_not_logged_in');
}
// ... rest of script
将
__DIR__
添加到 get_flagged_policies.php
中的目录解决了该问题。我也将require
更改为require_once
。
require_once __DIR__ . '/../session/validate_session_token.php';