PHP

HOW TO SET CORS COOKIES IN PHP

CORS FETCH TO SITE B fetch("https://site-b.com/2-demo.php", {   mode : "cors",   credentials : "include" });

SITE A - FETCH CALL TO SITE B

01

GET REQUEST ORIGIN  if (array_key_exists("HTTP_ORIGIN", $_SERVER)) { $origin = $_SERVER["HTTP_ORIGIN"]; } else if (array_key_exists("HTTP_REFERER", $_SERVER)) { $origin = $_SERVER["HTTP_REFERER"]; } else { $origin = $_SERVER["REMOTE_ADDR"]; } $origin = parse_url($origin, PHP_URL_HOST);

SITE B - SET CORS COOKIE (A)

02

CHECK ALLOWED if ($origin != site-a.com) { http_response_code(403); exit(); }

PROCEED SET COOKIE header("Access-Control-Allow-Origin: $origin"); header("Access-Control-Allow-Credentials: true"); setcookie("It", "Works", [   "expires" => time()+3600,   "path" => "/",   "domain" => ".site-b.com",   "secure" => true,   "samesite" => "None" ]); echo "OK";

SITE B - SET CORS COOKIE (B)

03