[英]Set a cookie on another domain using ajax and php - FAILS
Domain-Being-Browsed.com has a javascript function, which when triggered makes an ajax call to a php file on another domain: another-domain.com/set-cookie.php
set-cookie.php 包含如下代碼:
header("Access-Control-Allow-Origin: http://localhost:3000");
header("Access-Control-Allow-Credentials: true");
$cookie_set = FALSE;
$cookie_set = setcookie( 'cookie_name', 'cookie_value', $a_big_number, '/' );
if( $cookie_set ){ echo 'cookie set!'; }
javascript function是這樣的:
var url = 'http://another-domain.com/set-cookie.php';
$.ajax({
'url': url,
'xhrFields': {
withCredentials: true
}
}).done(function(resp){
console.log(resp);
});
如果我在瀏覽器中訪問http://another-domain.com/set-cookie.php ,它會設置 cookie。 If I trigger the javascript function, I get a response in the console, 'cookie set,', but when I load http://another-domain.com in my browser, I find that the cookie is not there.
我發現了這篇文章: Can't set cookie on different domain ,這看起來和我的一模一樣,但是給出的答案我已經合並了,但沒有幫助。 我錯過了什么?
按照 Barmar 的指示,我在開發工具中檢查了響應中的 Set-Cookie header 的網絡選項卡。 看來我需要將“SameSite”設置為“無”。 如果將“Samesite”設置為無,則還必須設置“安全”。 如果你設置了安全,你必須在 https 上加載頁面。 所以答案,如在此處的答案中找到: 如何修復“將 SameSite cookie 設置為無”警告? 就是像這樣更改 php 文件:
header("Access-Control-Allow-Origin: http://localhost:3000");
header("Access-Control-Allow-Credentials: true");
$cookie_options = array(
'expires' => time() + 60*60*24*30,
'path' => '/',
'secure' => true,
'samesite' => 'None'
);
$cookie_set = FALSE;
$cookie_set = setcookie( 'cookie_name', 'cookie_value', $cookie_options );
if( $cookie_set ){ echo 'cookie set!'; }
並在 https 上加載頁面。 作品!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.