Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active September 29, 2024 05:24
Show Gist options
  • Save code-boxx/487cd4f73f8a69bac9a26a5a1091602e to your computer and use it in GitHub Desktop.
Save code-boxx/487cd4f73f8a69bac9a26a5a1091602e to your computer and use it in GitHub Desktop.
PHP Cross Domain Cookie
<!DOCTYPE html>
<html>
<head>
<title>PHP CORS Set Cookie</title>
</head>
<body>
<!-- (A) DEMO BUTTON -->
<input type="button" value="CORS Cookie" onclick="demo()">
<script>
function demo () {
// (B) CORS FETCH TO SITE B
fetch("https://site-b.com/2-handler.php", {
mode : "cors",
credentials : "include"
})
// (C) FOR DEBUGGING, CONSOLE LOG ALL RESPONSES.
.then(res => {
console.log(res);
return res.text();
})
.then(res => console.log(res))
.catch(err => console.log(err));
}
</script>
</body>
</html>
<?php
// (A) 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"];
}
// (B) CHECK ALLOWED DOMAINS
if (!in_array(
parse_url($origin, PHP_URL_HOST),
["site-a.com", "site-b.com"]
)) {
http_response_code(403);
exit("$origin not allowed");
}
// (C) PROCEED - SET CORS 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";
<!DOCTYPE html>
<html>
<head>
<title>PHP CORS Set Cookie</title>
</head>
<body>
<div id="demo"></div>
<script>
document.getElementById("demo").innerHTML = document.cookie;
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment