【问题标题】:can't send messages and $username isn't displayed无法发送消息且 $username 未显示
【发布时间】:2022-01-10 03:59:02
【问题描述】:

我在 php 中做了一个聊天服务。当您进入聊天室时,它会显示“欢迎,--用户名--”。我的问题是我添加了一个登录字段,现在我无法发送消息并且不显示用户名。我到处寻找,但似乎因为我的代码是如此“独特”,似乎没有任何帮助。 --这一切都不是我自己做的,我用别人的代码来登录,用别人的代码来做服务本身。

login.php

<?php
    session_start();
    echo isset($_SESSION['login']);
    if(isset($_SESSION['login'])) {
      header('LOCATION:admin.php'); die();
    }
?>
<!DOCTYPE html>
<html>
   <head>
     <meta http-equiv='content-type' content='text/html;charset=utf-8' />
     <title>Login</title>
     <meta charset="utf-8">
     <meta name="viewport" content="width=device-width, initial-scale=1">
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
   </head>
<body>
  <div class="container">
    <h3 class="text-center">Login</h3>
    <?php
      if(isset($_POST['submit'])){
        $username = $_POST['username']; $password = $_POST['password'];
        if($username === 'admin' && $password === 'password'){
          $_SESSION['login'] = true; header('LOCATION:admin.php'); die();
        } {
          echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
        }
        if($username === 'admon' && $password === 'password'){
            $_SESSION['login'] = true; header('LOCATION:admin.php'); die();
          } {
            echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
          }
          
      }
    ?>
    <form action="" method="post">
      <div class="form-group">
        <label for="username">Username:</label>
        <input type="text" class="form-control" id="username" name="username" required>
      </div>
      <div class="form-group">
        <label for="pwd">Password:</label>
        <input type="password" class="form-control" id="pwd" name="password" required>
      </div>
      <button type="submit" name="submit" class="btn btn-default">Login</button>
    </form>
  </div>
</body>
</html>

admin.php

<?php
    session_start();
    if(!isset($_SESSION['login'])) {
        header('LOCATION:login.php'); die();
    }

    if(isset($_GET['logout'])){    
     
        //Simple exit message
        $logout_message = "<div class='msgln'><span class='left-info'>User <b class='user-name-left'>". $_SESSION['name'] ."</b> has left the chat session.</span><br></div>";
        file_put_contents("log.html", $logout_message, FILE_APPEND | LOCK_EX);
         
        session_destroy();
        header("Location: login.php"); //Redirect the user
    }

?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
 
        <title>English Pricks</title>
        <meta name="description" content="A Group Chat." />
        <link rel="stylesheet" href="style.css" />
    </head>
    <body>
        <div id="wrapper">
            <div id="menu">
                <p class="welcome">Welcome, <b><?php echo $username['username']; ?></b>&period; &nbsp;<a href="https://docs.google.com/document/d/1S2O4y2z_8Yu_mibQQGEU4E9pHdeckPfo5pI7FtM0YrI/edit" target="_blank">Image Dump&period;&period;&period;</a></p>
                <p>Emoji's &#8594;&nbsp;</p>
                <button id="emoji-button" style="border: none;">????</button>
                &nbsp;
                <p class="logout"><a id="exit" href="#">Leave</a></p>
            </div>
 
            <div id="chatbox">
            <?php
            if(file_exists("log.html") && filesize("log.html") > 0){
                $contents = file_get_contents("log.html");          
                echo $contents;
            }
            ?>
            </div>
 
            <form name="message" action="">
                <input name="usermsg" type="text" id="usermsg" style="outline: none;" spellcheck="true"/>
                <input name="submitmsg" type="submit" id="submitmsg" value="&#8593;" />
            </form>
        </div>
        <script type="text/javascript" src="./jquery.min.js"></script>
        <script src="emoji.js"></script>
    
    <script type="text/javascript">
      document.addEventListener('DOMContentLoaded', function () {
        var picker = new EmojiButton();
        var button = document.querySelector('#emoji-button');
        button.addEventListener('click', function () {
          picker.showPicker(button);
          picker.on('emoji', emoji => {
          document.querySelector('#usermsg').value += emoji;
        });
      });
    });
    </script>

<script type="text/javascript">
    $(document).ready(function () {
    $("#submitmsg").click(function(){   
    var clientmsg = $.trim($("#usermsg").val());
    if(clientmsg.length >= 1){ // Prevents Spamming the Enter Key
        $.post("post.php", {text: clientmsg});             
        $("#usermsg").val("");
    }else{
        
    }
    return false;
}); 
                function loadLog() {
                    var oldscrollHeight = $("#chatbox")[0].scrollHeight - 20; //Scroll height before the request
 
                    $.ajax({
                        url: "log.html",
                        cache: false,
                        success: function (html) {
                            $("#chatbox").html(html); //Insert chat log into the #chatbox div
 
                            //Auto-scroll           
                            var newscrollHeight = $("#chatbox")[0].scrollHeight - 20; //Scroll height after the request
                            if(newscrollHeight > oldscrollHeight){
                                $("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal'); //Autoscroll to bottom of div
                            }   
                        }
                    });
                }
 
                setInterval (loadLog, 1000);

                $("#exit").click(function () {
                    var exit = confirm("Are you sure you want to leave?");
                    if (exit == true) {
                    window.location = "index.php?logout=true";
                    }
                });
            });
        </script>
    </body>
</html>

【问题讨论】:

  • 什么是$username['username']?你是说$username 还是$_POST['username']
  • @SebastianSimon 是的,我的意思是 $username

标签: javascript php html jquery


【解决方案1】:

login.php 文件中,if 块中缺少 else,为了查看 用户名,您应该以相同的方式将其添加到 $_SESSION就像你做的那样 $_SESSION['login'],因为我在提供的代码中看不到任何其他可以用作临时存储的东西。另一个问题是您在 html 代码中放置了带有登录和密码检查的 header() 函数。这将在运行时标头已发送触发警告。为了避免将您的检查代码放在文件顶部,并检查&lt;?php php 开始标记之前或之后是否没有空格。

您可以在下面找到固定 login.php 文件的示例。

<?php
  session_start();

  function setSessionData($name, $value) {
    $_SESSION[$name] = $value;
  }

  function redirectWithData($username = '') {
    setSessionData('login', true);
    setSessionData('username', $username);
    header('Location:admin.php'); 
    die();
  }

  if(isset($_SESSION['login'])) {
    header('Location:admin.php'); die();
  }

  if(isset($_POST['submit'])) {
    $username = $_POST['username']; $password = $_POST['password'];
    if($username === 'admin' && $password === 'password'){
      redirectWithData($username);
    } elseif($username === 'admon' && $password === 'password'){
      redirectWithData($username);
    } else  {
        echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
    }
  }
?>
<!DOCTYPE html>
<html>
   <head>
     <meta http-equiv='content-type' content='text/html;charset=utf-8' />
     <title>Login</title>
     <meta charset="utf-8">
     <meta name="viewport" content="width=device-width, initial-scale=1">
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
   </head>
<body>
  <div class="container">
    <h3 class="text-center">Login</h3>
    <form action="" method="post">
      <div class="form-group">
        <label for="username">Username:</label>
        <input type="text" class="form-control" id="username" name="username" required>
      </div>
      <div class="form-group">
        <label for="pwd">Password:</label>
        <input type="password" class="form-control" id="pwd" name="password" required>
      </div>
      <button type="submit" name="submit" class="btn btn-default">Login</button>
    </form>
  </div>
</body>
</html>

然后您可以在管理页面上显示用户名 Welcome, &lt;b&gt;&lt;?php echo $_SESSION['username']; ?&gt;

关于admin.php 功能。根据 post.php 文件中的 JavaScript 代码添加消息的逻辑。

$.post("post.php", {text: clientmsg});

那么,为什么添加或不添加很难回答)

顺便说一句,在您的注销逻辑中 admin.php 文件更改 window.location = "index.php?logout=true"; -> window.location = "?logout=true"; 它将回退到您已经拥有重定向逻辑的同一页面。

【讨论】:

  • 是的,谢谢!对于 post.php 我必须添加 $_SESSION['username']; 以便它发送文本
猜你喜欢
  • 2022-11-03
  • 2016-05-09
  • 2015-12-30
  • 1970-01-01
  • 2021-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多