登录后PHP不显示用户名

我正在从头开始学习 php 和 html,我有这个项目,我想在其中显示登录后的用户名。


我已经声明:


<a>Hello, <?php 

                        if(isset($_SESSION['username'])){

                            echo $_SESSION['username'];

                        } else {

                            echo "user";

                        }


                        ?>

                        </a>

在我希望显示用户名的 html 字段中。它以前有效。但是,注销后,用户名不再存在。


这是注销的代码:


<?php


     session_start();

     session_unset();

     header("location:index.php");

     exit();


?>

登录的那个:


<?php 

session_start();



$user = $_POST['login'];

$pass = md5($_POST['pword']);

$entrar = $_POST['entrar'];

$conn = mysqli_connect("localhost","root", "", "pdsys", "3308");


if(isset($entrar)){

    $verifica = mysqli_query($conn,"SELECT * FROM users WHERE username = '$user' AND pword = '$pass'") or die ("Usuário ou senha incorretos");

    if (mysqli_num_rows($verifica)<=0){

        echo "<script language='javascript' type='text/javascript'>

        alert('Login e/ou senha incorretos');window.location

        .href='index.php';</script>";

        die();

    } else {

        setcookie("login", $user);

        header("location: main.php");

    }

}?>

我认为它可能与 session_destroy() 有关,但我不知道如何让它再次工作。它只显示“用户”。


其他一切都是功能性的 = 与数据库、登录系统等的连接。



慕运维8079593
浏览 89回答 2
2回答

一只萌萌小番薯

使用session_destroy();在注销功能中。

红糖糍粑

通过添加一行来设置会话用户名的值来解决这个问题:<?php&nbsp;session_start();$user = $_POST['login'];$pass = md5($_POST['pword']);$entrar = $_POST['entrar'];$conn = mysqli_connect("localhost","root", "", "pdsys", "3308");if(isset($entrar)){&nbsp; &nbsp; $verifica = mysqli_query($conn,"SELECT * FROM users WHERE username = '$user' AND pword = '$pass'") or die ("Usuário ou senha incorretos");&nbsp; &nbsp; if (mysqli_num_rows($verifica)<=0){&nbsp; &nbsp; &nbsp; &nbsp; echo "<script language='javascript' type='text/javascript'>&nbsp; &nbsp; &nbsp; &nbsp; alert('Login e/ou senha incorretos');window.location&nbsp; &nbsp; &nbsp; &nbsp; .href='index.php';</script>";&nbsp; &nbsp; &nbsp; &nbsp; die();&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; setcookie("login", $user);&nbsp; &nbsp; &nbsp; &nbsp; $_SESSION['username']=$user;&nbsp; &nbsp; &nbsp; &nbsp; header("location: main.php");&nbsp; &nbsp; }}?>
打开App,查看更多内容
随时随地看视频慕课网APP