Ajax重置PHP会话 [英] Ajax resets PHP session
问题描述
我知道,因此我提前道歉,但是我已经多次解决了他的解决方案,因此在我的情况下无法解决会话重置的问题.
I know this question has been asked before so I apologize ahead of time, but I have gone over his solution multiple times and it does not fix the session reset in my case.
我有一个简单的php页面,该页面输出用于调试的会话ID.像这样:
I have a simple php page that outputs a session id for debugging. Like this:
<?php
session_start();
echo session_id();
?>
然后,我有一个带有 jQuery
的简单HTML页面,该页面在该页面上执行 ajax
请求并记录输出.
Then I have a simple HTML page with jQuery
that performs an ajax
request on that page and logs the output.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$.post('http://localhost.api.mydomain/sid', {
some: 'data'
}, function(data,status) {
console.log(data);
});
</script>
</head>
<body>
Check your console.
</body>
</html>
如果我手动访问url http://localhost.api.mydomain/sid
,则输出不会改变, session_id()
保持不变.但是,如果刷新ajax页面,则每次刷新时输出的 session_id()
都会更改.
If I manually visit the url http://localhost.api.mydomain/sid
the output never changes, the session_id()
stays constant, as expected. However, if I refresh the ajax page, the outputted session_id()
changes with every refresh.
我尝试在 php.ini
文件中设置 session.cookie_domain
,但无济于事.对于这个问题,我深表歉意,但我根本找不到解决方法.
I've tried setting session.cookie_domain
in the php.ini
file but to no avail. I apologize for this issue, but I simply cannot find a solution.
推荐答案
这是一个访问控制
问题,而不是 ajax
问题.
This is an Access-Control
issue, not an ajax
issue.
当您直接从浏览器访问该URL时,您正在从您所访问的域中请求一个(会话)Cookie.在这种情况下,当您使用 ajax
时,您是从不是您要访问的域的域中请求Cookie.
When you visit the url from your browser directly, you are requesting a (session) cookie from the domain you are visiting. When you are using ajax
, in this case, you are requesting a cookie from a domain that is not the domain you are visiting.
在位于 api.example.com
的php API文件上,尝试执行此操作.
On your php API file at api.example.com
, try this.
header('Access-Control-Allow-Origin: example.com');
header('Access-Control-Allow-Credentials: true');
然后在您的 ajax
请求文件中,像这样使用 xhrFields
参数.
Then on your ajax
request file, use the xhrFields
parameter like so.
$.ajax({
url: 'https://api.example.com',
xhrFields: { withCredentials: true },
success: function(data) {
console.log(data)
}
});
现在,只要您从始发地 example.com
调用请求,cookie就会表现出预期的效果.
Now as long as you are calling the request from the origin example.com
, cookies will behave as expected.
这篇关于Ajax重置PHP会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!