带有PHP标头的跨域请求标头(CORS)


146

我有一个简单的PHP脚本,正在尝试跨域CORS请求:

<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
...

但是我仍然得到错误:

请求标头字段X-Requested-With不允许Access-Control-Allow-Headers

我有什么想念的吗?

Answers:


59

Access-Control-Allow-Headers不允许*作为可接受的值,请参见此处的Mozilla文档。

您应该发送可接受的标头(而不是如星号所示)而不是星号X-Requested-With


289

妥善处理CORS请求要花些时间。这是一个可以更充分(正确)响应的功能。

/**
 *  An example CORS-compliant method.  It will allow any GET, POST, or OPTIONS requests from any
 *  origin.
 *
 *  In a production environment, you probably want to be more restrictive, but this gives you
 *  the general idea of what is involved.  For the nitty-gritty low-down, read:
 *
 *  - https://developer.mozilla.org/en/HTTP_access_control
 *  - http://www.w3.org/TR/cors/
 *
 */
function cors() {

    // Allow from any origin
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        // Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
        // you want to allow, and if so:
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }

    // Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            // may also be using PUT, PATCH, HEAD etc
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

        exit(0);
    }

    echo "You have CORS!";
}

32
请注意,将HTTP Origin值发送回允许的源将使任何人都可以使用Cookie向您发送请求,从而潜在地窃取了登录您网站并查看攻击者页面的用户的会话。您要么要发送“ *”(这将禁止cookie从而防止会话窃取),要么发送您希望站点工作的特定域。
Jules

1
同意 实际上,您可能不会只允许任何旧域使用CORS服务,而是将其限制为您决定信任的某个集合。
slashingweapon'8

仅供参考,此解决方案仅对我Linux serverIISIIS
有用

1
谢谢!必须为此答案添加书签。太糟糕了,我们不能将其标记为新答案
Ascherer

1
唯一真正有效的方法!..只需更改Access-Control-Allow-Origin:*到Access-Control-Allow-Origin:{$ _SERVER ['HTTP_ORIGIN']}
Renan Franca

60

我遇到了同样的错误,并在后端脚本中使用以下PHP进行了修复:

header('Access-Control-Allow-Origin: *');

header('Access-Control-Allow-Methods: GET, POST');

header("Access-Control-Allow-Headers: X-Requested-With");

35

互联网上的许多描述都没有提到仅凭指定Access-Control-Allow-Origin是不够的。这是一个对我有用的完整示例:

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: POST, GET, DELETE, PUT, PATCH, OPTIONS');
        header('Access-Control-Allow-Headers: token, Content-Type');
        header('Access-Control-Max-Age: 1728000');
        header('Content-Length: 0');
        header('Content-Type: text/plain');
        die();
    }

    header('Access-Control-Allow-Origin: *');
    header('Content-Type: application/json');

    $ret = [
        'result' => 'OK',
    ];
    print json_encode($ret);

1
请解释为什么这还不够,什么最小的例子足够了。
halfpastfour.am

不幸的是,我不记得确切了,现在没有时间再进行调查,但是,正如我记得的那样,网络服务器/浏览器方面的一些基本假设使其无法正常工作。这是最适合我的最小代码。
Csongor Halmai

24

我只是设法让dropzone和其他插件可以使用此修复程序(angularjs + php后端)

 header('Access-Control-Allow-Origin: *'); 
    header("Access-Control-Allow-Credentials: true");
    header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
    header('Access-Control-Max-Age: 1000');
    header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token , Authorization');

将其添加到您的upload.php或发送请求的位置(例如,如果您具有upload.html,并且需要将文件附加到upload.php,然后复制并粘贴这4行)。另外,如果您在chrome / mozilla中使用CORS插件/附件,请务必将它们切换一次以上,以便启用CORS


15

如果要从PHP创建CORS服务,则可以将此代码用作处理请求的文件的第一步:

// Allow from any origin
if(isset($_SERVER["HTTP_ORIGIN"]))
{
    // You can decide if the origin in $_SERVER['HTTP_ORIGIN'] is something you want to allow, or as we do here, just allow all
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
}
else
{
    //No HTTP_ORIGIN set, so we allow any. You can disallow if needed here
    header("Access-Control-Allow-Origin: *");
}

header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 600");    // cache for 10 minutes

if($_SERVER["REQUEST_METHOD"] == "OPTIONS")
{
    if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_METHOD"]))
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT"); //Make sure you remove those you do not want to support

    if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_HEADERS"]))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

    //Just exit with 200 OK with the above headers for OPTIONS method
    exit(0);
}
//From here, handle the request as it is ok

8

如果我们不能正确理解CORS的功能,那么CORS可能会令人头疼。我在PHP中使用它们,它们可以正常工作。这里参考

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 1000");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");
header("Access-Control-Allow-Methods: PUT, POST, GET, OPTIONS, DELETE");

7

当将angular 4用作客户端并将PHP用作服务器端时,这些代码对我来说无效。

header("Access-Control-Allow-Origin: *");

3

这应该工作

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");

0

将此代码添加到.htaccess中

在标题中添加自定义身份验证密钥,例如app_key,auth_key..etc

Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers: "customKey1,customKey2, headers, Origin, X-Requested-With, Content-Type, Accept, Authorization"

-1

在Windows中,将此命令粘贴到运行窗口中只是为了测试代码

chrome.exe --user-data-dir =“ C:/ Chrome开发者会话” --disable-web-security


甚至暂时禁用浏览器的网络安全是一个可怕的主意
Machavity
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.