PHP 헤더가있는 CORS
도메인 간 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);
I've simply managed to get dropzone and other plugin to work with this fix (angularjs + php backend)
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');
add this in your upload.php or where you would send your request (for example if you have upload.html and you need to attach the files to upload.php, then copy and paste these 4 lines). Also if you're using CORS plugins/addons in chrome/mozilla be sure to toggle them more than one time,in order for CORS to be enabled
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
CORS can become a headache, if we do not correctly understand its functioning. I use them in PHP and they work without problems. reference here
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");
This much code works down for me when using angular 4 as the client side and PHP as the server side.
header("Access-Control-Allow-Origin: *");
this should work
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");
add this code in .htaccess
add custom authentication key's in header like 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"
참고URL : https://stackoverflow.com/questions/8719276/cors-with-php-headers
'programing tip' 카테고리의 다른 글
AppCompat 라이브러리에서 SwitchCompat의 색상을 변경하는 방법 (0) | 2020.07.13 |
---|---|
Rails 콘솔에서 멋진 포맷을 얻는 방법 (0) | 2020.07.13 |
UIImageView에서 코너 반경 설정이 작동하지 않습니다 (0) | 2020.07.13 |
groovy 배열 / 해시 / 컬렉션 / 목록의 요소를 확인하는 방법은 무엇입니까? (0) | 2020.07.13 |
diff를 git-diff처럼 작동시키는 방법? (0) | 2020.07.12 |