未定义索引:用户注销时的用户名错误

时间:2018-03-01 22:35:33

标签: php html session login logout

这是我的index.php代码的一部分,它打印当前用户登录$ SESSION。但是当用户单击logout时,它会在第x行上显示一条错误消息“Undefined index:username”。 这是什么意思,我该如何解决?

 <?php

  $dbname = 'lw17894'; # Change to your username
  $dbuser = 'lw17894';
  $dbpass = 'obscure';
  $dbhost = 'localhost';

  $link = mysqli_connect( $dbhost, $dbuser, $dbpass )
  or die( "Unable to Connect to '$dbhost'" );

  mysqli_select_db( $link, $dbname )
  or die("Could not open the db '$dbname'");


    if($_SESSION['username']) {
        echo "Welcome, User: {$_SESSION['username']}";
    } else {
        echo "User not logged in!";
    }
    ?>

并且继承我的logout.php代码:

<?php
session_start()
?>
<!DOCTYPE html>
<html>
<body>

<?php
session_unset(); 
session_destroy();
echo "<h1>You are logged out!</h1>";
echo "<br>";
echo "<h2><strong>You will be redirected back to Home in 3 seconds</strong></h2>";
?>
<meta http-equiv="refresh" content="3;URL=index.php" />
</body>
</html>

2 个答案:

答案 0 :(得分:1)

由于会话被破坏,请尝试使用isset($ _ SESSION)&amp;&amp; isset($ _ SESSION ['username'])在if语句中。

答案 1 :(得分:0)

当用户未登录时,您仍在检查会话变量中的用户名密钥。

检查是否有会话,并且会话中存在用户名密钥。

  $dbname = 'lw17894'; # Change to your username
  $dbuser = 'lw17894';
  $dbpass = 'obscure';
  $dbhost = 'localhost';

  $link = mysqli_connect( $dbhost, $dbuser, $dbpass )
  or die( "Unable to Connect to '$dbhost'" );

  mysqli_select_db( $link, $dbname )
  or die("Could not open the db '$dbname'");

    if (session_status() != PHP_SESSION_NONE) {
        if(array_key_exists ('username' , $_SESSION ) {
            echo "Welcome, User: {$_SESSION['username']}";
        } else {
            echo "User not logged in!";
        }
    }