【问题标题】:PHP session failedPHP 会话失败
【发布时间】:2014-11-20 11:28:19
【问题描述】:

文件1.php

我的 php 会话在这里失败了。我不能使用我的会话变量“用户名”。

$count = mysqli_num_rows($authentification); 

    if ($count==1) {
        session_start();
        $_SESSION['username'] = $username; 
        header("location: home.php");

        } 
        else {
                echo"<script language='javascript'> alert('entered information is not correct'); </script>";
                header("location:portal.php");

        }

这是我继续会话的另一个文件

file2.php

session_start();
$username=$_SESSION["username"];

if($_SESSION["username"]){
    echo $output = "<h2><div id='bonjour'>\t<p><b>Bonjour $username, nous sommes le ".date("d-m-Y").", il est <span id='heureH'>".date('H:i:s')."</span>.</b></p></div>\r\n</h2>";

}else{
    echo"Session failed";
}

当我在浏览器上看到它显示“会话失败”。你能告诉我缺少什么吗?我是 php 新手

【问题讨论】:

  • 你的 $username 变量中有什么?
  • 您最初设置用户名的页面上是否有session_start();
  • 把你的 session_start(); @文件顶部
  • @kidz:是的,在我使用会话变量“用户名”之前,我在两个文件中都有 session_start()
  • @Naincy Gupta:在文件 1 还是文件 2 中?

标签: php mysql session


【解决方案1】:

不要在 if 条件下开始会话。从文件顶部开始。如果$count 不是 1,那么您不会开始会话。

注意:在header("location:portal.php"); 之后和header("location:portal.php"); 之前添加exit; 不要使用echo 创建输出

【讨论】:

  • 我已经做了你写的修改。但仍然显示相同的消息。还有什么遗漏吗?
【解决方案2】:

我在使用 Mac Os Safari 浏览器时遇到了这种情况。我使用此代码使其工作:

$currentCookieParams = session_get_cookie_params();
session_set_cookie_params(86400,$currentCookieParams["path"], $currentCookieParams["domain"], 
true, // cookie_secure
true  // cookie_httponly
);

你必须把它放在之前 session_start();

86400 = 1 天会话生命周期

【讨论】:

  • 是否有充分的理由在您的应用程序中进行配置,而不是在全局 php.ini 中配置?
  • @NicoHaase:不——没有特殊原因。这只是一个概念证明。如果这个解决方案有效,那么 php.ini 方式肯定会更好。
【解决方案3】:

在编写任何其他代码之前,在文件的最顶部开始会话,就像在第二个示例中所做的那样

session_start();
$count = mysqli_num_rows($authentification); 

    if ($count==1) {
        $_SESSION['username'] = $username; 
        header("location: home.php");

        } 
        else {
                echo"<script language='javascript'> alert('entered information is not correct'); </script>";
                header("location:portal.php");

        }

【讨论】:

    【解决方案4】:

    我猜你的第二个 sn-p 中的第二个 session_start() 导致 $_SESSION 数组被重置。

    【讨论】:

      猜你喜欢
      • 2011-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-10
      相关资源
      最近更新 更多