基于 PHP 的 session 变量不保留值。适用于本地主机,但不适用于服务器

标签 php

我已经尝试调试这个问题好几个小时了,但无济于事。我已经使用 PHP 很多年了,在中断很长时间后又重新开始使用它,所以我还是有点生疏。

无论如何,由于我无法弄清楚的某些原因,我的 $_SESSION 变量没有保留它们的值(value)。该网站在本地主机上运行完美,但将其上传到服务器似乎无法正常运行。

我首先检查的是 PHP.ini 服务器设置。一切似乎都很好。事实上,我的登录系统是基于 session 的,并且运行良好。所以现在我知道 $_SESSIONS 工作正常并为我的登录保留它们的值,我假设服务器已设置并且问题出在我的脚本中。

这是导致问题的代码的精简版本。 $type、$order 和 $style 在通过 GET 变量设置后不会被保留。用户单击一个链接,该链接通过 GET 设置一个变量,并且该变量在他们的 session 的剩余时间内保留。

我的逻辑是否存在我没​​有发现的问题?

<?php
require_once('includes/top.php'); //first line includes a call to session_start();
require_once('includes/db.php');

$type = filter_input(INPUT_GET, 't', FILTER_VALIDATE_INT);
$order = filter_input(INPUT_GET, 'o', FILTER_VALIDATE_INT);
$style = filter_input(INPUT_GET, 's', FILTER_VALIDATE_INT);

/*
According to documentation, filter_input returns a NULL when variables
are undefined. So, if t, o, or s are not set via URL, $type, $order and $style
will be NULL. 
*/    

print_r($_SESSION);
/* 
All other sessions, such as the login session, etc. are displayed here. After 
the sessions are set below, they are displayed up here to... simply with no value. 
This leads me to believe the problem is with the code below, perhaps?
*/


// If $type is not null (meaning it WAS set via the get method above)
// or it's false because the validation failed for some reason,
// then set the session to the $type. I removed the false check for simplicity.
// This code is being successfully executed, and the data is being stored...
if(!is_null($type))
{
    $_SESSION['type'] = $type;
}
if(!is_null($order))
{
    $_SESSION['order'] = $order;
}
if(!is_null($style))
{
    $_SESSION['style'] = $style;
}


 $smarty->display($template);

?>

如果有人能指出正确的方向,我将不胜感激。谢谢。

最佳答案

难以置信!

调试了三个小时,问题解决了

HostGator,我不再钟爱的主机,在 register_globals ON 下运行它们的默认 ini

我简直不敢相信。

所以我的 $type 变量被 $_SESSION['type'] 覆盖,并且它们被视为相同。所以这是导致问题的服务器问题,而不是我的编码。很高兴知道这一点,但我想要 5 个小时的时间把我的头发拉回来。

我希望这能帮助那些正在使用 HostGator 并且感到困惑的人。

关于基于 PHP 的 session 变量不保留值。适用于本地主机,但不适用于服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2475114/

相关文章:

php - 如何编辑 vscode 的默认 php linter?

php - 在 Twig 中是相同的 (===)

php - 仅从 cli 调用未定义的函数 oci_connect(在 html 中工作正常)

php - 如何加快我网站上的图像加载时间?

javascript - 工作和整合 Paypal 支付专业版

php - Javascript、AJAX 和 PHP 帮助

php - 来自 Javascript 的查询字符串参数无法处理 PHP 脚本

php - 将 PHP 简化为 MySQL

php - Ajax 表单未提交

php - 根据 Woocommerce 订单状态禁用特定付款方式