Cross-Origin Request Headers(CORS) with PHP headers

后端 未结 11 1359
情书的邮戳
情书的邮戳 2020-11-21 11:13

I have a simple PHP script that I am attempting a cross-domain CORS request:



        
11条回答
  •  悲哀的现实
    2020-11-21 11:39

    If you want to create a CORS service from PHP, you can use this code as the first step in your file that handles the requests:

    // 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
    

提交回复
热议问题