[php] PHP 헤더가있는 CORS (Cross-Origin Request Headers)

도메인 간 CORS 요청을 시도하는 간단한 PHP 스크립트가 있습니다.

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

그러나 여전히 오류가 발생합니다.

요청 헤더 필드 X-Requested-With는 허용되지 않습니다.Access-Control-Allow-Headers

내가 놓친 게 있습니까?



답변

Access-Control-Allow-Headers허용 *되는 값으로 허용 되지 않는 경우 여기 에서 Mozilla 문서를 참조 하십시오 .

별표 대신 허용 된 헤더를 보내야합니다 (먼저 X-Requested-With오류가 표시 한대로)


답변

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!";
}


답변

같은 오류가 발생하여 백엔드 스크립트에서 다음 PHP로 수정했습니다.

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

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

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


답변

인터넷 전체의 많은 설명에서는 지정 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);


답변

나는이 수정 프로그램 (angularjs + PHP 백엔드)과 함께 작동하기 위해 dropzone 및 기타 플러그인을 얻었습니다.

 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를 사용하도록 설정하려면 한 번 이상 전환해야합니다.


답변

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


답변

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");