简体   繁体   English

为什么PHP会话不在页面之间保存变量?

[英]Why is PHP session not saving the variable between pages?

I am setting up an admin panel for a website, and everything was working fine on my local (MAMP) server. 我正在为一个网站设置一个管理面板,一切都在我的本地(MAMP)服务器上正常工作。 I uploaded the website to the server and the user authentication isn't working anymore. 我将网站上传到服务器,用户身份验证不再有效。 I am able to get a success from the server, but when I'm entering into a page, PHP can't find the required session variable, and thus redirects the user back to the sign in page. 我能够从服务器获得成功,但是当我进入页面时,PHP无法找到所需的会话变量,从而将用户重定向回登录页面。

I have tried on both PHP version 5 and 7. I have tried echoing the session variable upon verification. 我已经尝试了PHP版本5和7.我已经尝试在验证时回显会话变量。 I have tried to simply store the variable on one page and reading it on another page in the same folder, and it didn't work as well. 我试图简单地将变量存储在一个页面上并在同一文件夹中的另一个页面上读取它,但它也不能正常工作。

page1.php page1.php中

<?php
session_start();
$_SESSION["userid"] = 1;
?>
<a href="page2.php">To Page2</a>

page2.php 使page2.php

<?php
session_start();
if (!isset($_SESSION["userid"])) {
    header("Location: page1.php");
    die();
}

echo $_SESSION["userid"];

After I click the link in page1.php, page2.php redirects me to page1.php again without any error. 单击page1.php中的链接后,page2.php再次将我重定向到page1.php而没有任何错误。

Is your website using some load balancer? 您的网站是否使用了一些负载均衡器?

By default, PHP creates the session on server memory. 默认情况下,PHP在服务器内存上创建会话。 So, if your website is using a different server for each request, the $_SESSION set values are lost. 因此,如果您的网站为每个请求使用不同的服务器,则$ _SESSION设置值将丢失。 In this case, a good solution could be store sessions out of the server, maybe in a Redis or Memcached. 在这种情况下,一个好的解决方案可能是服务器外的存储会话,可能是Redis或Memcached。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM