PHP - 标头/配置“允许来源”不起作用
Posted
技术标签:
【中文标题】PHP - 标头/配置“允许来源”不起作用【英文标题】:PHP - headers/config "allow origin" not working 【发布时间】:2020-05-16 09:02:07 【问题描述】:我的标头不起作用,一旦我请求一个需要“授权”标头的站点,我就会收到一个 cors 错误。看来,我可以将所有可能的值放入 Allow-Origin 并输出相同的结果(我仍然可以访问所有不需要授权的站点,即使 Allow-Origin 设置为随机值,例如“www.zzzawhdhawd .com”)。我也可以发出 GET 请求,尽管我显然只允许 POST。
我有一个rest API,每个api文件都是这样开始的
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
我的 apache2.conf 看起来像这样
# Allow Origin
Header set Access-Control-Allow-Origin '*'
.htaccess
# Turn on the rewrite engine
RewriteEngine on
# If the request doesn't end in .php (Case insensitive) continue processing rules
RewriteCond %REQUEST_URI !\.php$ [NC]
# If the request doesn't end in a slash continue processing the rules
RewriteCond %REQUEST_URI [^/]$
RewriteCond %REQUEST_FILENAME !-f
# Rewrite the request with a .php extension. L means this is the 'Last' rule
RewriteRule ^(.*)$ $1.php [L]
Header set Access-Control-Allow-Origin '*'
我是否正确实现了标题?
【问题讨论】:
【参考方案1】:GET 方法未添加到标题中。 试试这样的改变。
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
如果它不起作用,请尝试这样的标题:
$headers = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, PATCH, DELETE',
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Max-Age' => '86400',
'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With'
];
foreach ($headers as $key => $value)
header($key . ': ' . $value);
【讨论】:
以上是关于PHP - 标头/配置“允许来源”不起作用的主要内容,如果未能解决你的问题,请参考以下文章