I can't figure out why the Javascript Fetch API stubbornly refuses to keep my PHP session. Here is a minimal test:
<?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
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
I found several similar questions/answers, but none of them helped. The suggested solution is to provide the Credentials option with 'include' or 'same-site', but none of them work.
I know that I can pass the session ID but if possible would like to avoid it.
Thanks for your help
I finally found the origin of the issue. This happened because I'm not in SSL (I'm on localhost) and sent this header from my .htaccess:
Header always edit Set-Cookie (.*) "$1; Secure"
I first checked my cookies with var_dump(session_get_cookie_params());
and it returned ["secure"]=> bool(false)
Useful to know:
in PHP session_get_cookie_params()
returns a wrong value if the cookie param is set into .htaccess
This is because the function is reading the php.ini value, not the value sent with .htaccess