Fetch Api - 如何将 PHP SESSION 数据发送到目标 PHP 文件?

问题描述 投票:0回答:2

我不明白为什么 Javascript Fetch API 顽固地拒绝保留我的 PHP 会话。这是一个最小的测试:

loader.php

<?php
session_start();
$_SESSION['test'] = 'OK';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
</head>
<body>
    <p>Origin session id is <?php echo session_id() ?></p>
    <div id="target"></div>
    <script>
        fetch('data.php', {
            method: 'get',
            credentials: 'include'
        }).then(response => response.text()).then((data) => {
            document.getElementById('target').innerHTML = data;
        }).catch(function (error) {
            console.log(error);
        });
    </script>
</body>
</html>

数据.php:

<?php
session_start();

echo '<p>Target session id is ' .  session_id() . '</p>';
if (empty($_SESSION)) {
    echo '<p>session is empty</p>';
} else {
    echo implode('<br>', $_SESSION);
}

结果:

Origin session id is abe10f9c611066f6400b2ce3d0ee8f97
Target session id is a68e76bf1d5180d79d27a2bcfa3c462c
session is empty

我发现了几个类似的问题/答案,但没有一个有帮助。 建议的解决方案是为凭据选项提供“include”或“same-site”,但它们都不起作用。

我知道我可以传递会话 ID,但如果可能的话希望避免它。

感谢您的帮助

javascript php session fetch-api
2个回答
0
投票

服务器上是否启用了

session.cookie_httponly
?如果是这样,那么将阻止 javascript 调用使用 cookie(一般来说,PHP 会话往往由 cookie 支持)。在此设置的上下文中,
http-only
意味着“
http
/
https
允许;
javascript
/
webassembly
/... 拒绝”。

您可能可以通过

phpinfo();
查看当前值。或在 php.net 上阅读更多相关信息。


0
投票

我终于找到问题的根源了。发生这种情况是因为我不在 SSL 中(我在本地主机上)并从我的 .htaccess 发送了此标头:

Header always edit Set-Cookie (.*) "$1; Secure"

我首先用

var_dump(session_get_cookie_params());
检查了我的 cookie,它返回了
["secure"]=> bool(false)

有用的知识:

在 PHP 中

session_get_cookie_params()
如果将 cookie 参数设置为 .htaccess

,则会返回错误值

这是因为该函数正在读取 php.ini 值,而不是通过 .htaccess 发送的值

© www.soinside.com 2019 - 2024. All rights reserved.