복붙노트

CORS 작동하지 않는 PHP

PHP

CORS 작동하지 않는 PHP

CORS를 통해 www.siteone.com에서 www.sitetwo.com으로 양식 데이터를 게시하려고합니다. 내 아약스 코드는 다음과 같습니다.

<script>
$(document).ready(function(){
        $("#submit").live('click',function() {
            var url = "http://www.sitetwo.com/cors.php";
            var data = $('#form').serialize();
            jQuery.ajax({
                url : url,
                type: "POST",
                data : $('#form').serialize(),
                }).done(function(response){
                    alert(response);
                    }).fail(function(error){
                    console.log(error.statusText);
                    });
                return false;


});
});
</script>

www.sitetwo.com에있는 cors.php 파일은 다음과 같습니다.

<?php
 header('Access-Control-Allow-Origin: *');
 header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
 echo "hai";
?>

그러나 여전히 Access-control-Allow-Origin 오류가 발생합니다. 발생 된 오류는 다음과 같습니다.

XMLHttpRequest cannot load http://www.sitetwo.com/cors.php. Origin http://www.siteone.com is not allowed by Access-Control-Allow-Origin. 

CORS를 사용하여 헤더를 통해 원격 웹 사이트를 허용함으로써 교차 도메인 요청을 사용할 수 있음을 알게되었습니다. 하지만 이렇게 해보면 오류가 발생합니다. 여기에 뭐가 빠졌는데? 내 요청 / 응답 헤더는 다음과 같습니다.

Response Headers
Connection  Keep-Alive
Content-Length  487
Content-Type    text/html; charset=iso-8859-1
Date    Fri, 23 Aug 2013 05:53:20 GMT
Keep-Alive  timeout=15, max=99
Server  Apache/2.2.15 (CentOS)
WWW-Authenticate    Basic realm="Site two Server - Restricted Area"
Request Headers
Accept  */*
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Content-Length  43
Content-Type    application/x-www-form-urlencoded; charset=UTF-8
Host    www.sitetwo.com
Origin  http://www.siteone.com
Referer http://www.siteone.com/index.html
User-Agent  Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:23.0) Gecko/20100101 Firefox/23.0

해결법

  1. ==============================

    1.마지막으로, 나는 나 자신이 문제에서 설명한 문제를 해결했다. 헤더에 액세스하기 위해 구현 한 코드가 올바르지 않습니다.

    마지막으로, 나는 나 자신이 문제에서 설명한 문제를 해결했다. 헤더에 액세스하기 위해 구현 한 코드가 올바르지 않습니다.

    아래에 언급 된 두 개의 라인 코드가 주어지면 작동하지 않습니다.

    <?php
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
    ?>
    

    그러나 CORS 요청을 적절하게 처리하는 것은 다소 복잡합니다. 보다 완벽하게 응답 할 함수가 있습니다. 업데이트 된 코드는 다음과 같습니다.

     <?php
        // Allow from any origin
        if (isset($_SERVER['HTTP_ORIGIN'])) {
            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']))
                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!";
    ?>
    

    다른 게시물에서 찾았습니다. 그것은 일했다 ....

  2. from https://stackoverflow.com/questions/18382740/cors-not-working-php by cc-by-sa and MIT license