
本教程旨在解决php聊天服务中,集成登录功能后出现的用户名无法显示和消息无法发送的问题。文章详细分析了php会话管理、条件判断逻辑以及`header()`重定向函数使用不当导致的常见错误,并提供了优化后的代码示例,帮助开发者正确存储用户会话数据、确保页面重定向的准确性,从而恢复聊天服务的核心功能。
在PHP聊天服务中集成登录功能后,出现消息无法发送和用户名无法显示的问题,通常是由于以下几个方面的原因:
原代码在admin.php中尝试通过来显示用户名。然而,$username变量仅在login.php的表单提交处理逻辑中被定义,并且是一个局部变量。它并未被存储到会话中,因此在admin.php页面中是无法直接访问到的。要解决此问题,需要将登录成功的用户名存储到PHP的$_SESSION全局变量中,以便在其他页面中获取。
根据admin.php中的JavaScript代码,消息的发送是通过AJAX请求post.php来完成的:$.post("post.php", {text: clientmsg});。由于post.php文件的具体实现未提供,我们无法直接诊断其内部问题。但是,如果登录流程本身存在缺陷(例如,用户未能成功登录导致会话未正确建立或用户身份未被post.php识别),可能会间接影响消息的发送功能。本教程将重点解决登录和用户名显示问题,为消息发送功能的正常运作奠定基础。
login.php文件中存在以下几个关键问题:
立即学习“PHP免费学习笔记(深入)”;
为了解决上述问题,我们将对login.php和admin.php进行如下优化:
核心思想是将所有PHP处理逻辑(包括会话启动、登录验证和重定向)前置到HTML内容输出之前。同时,引入辅助函数以提高代码可读性和复用性,并确保用户名被正确存储到会话中。
<?php
session_start(); // 始终在任何输出之前启动会话
// 辅助函数:设置会话数据
function setSessionData($name, $value) {
$_SESSION[$name] = $value;
}
// 辅助函数:重定向到admin页面并设置会话数据
function redirectWithData($username = '') {
setSessionData('login', true);
setSessionData('username', $username); // 将用户名存储到会话中
header('Location:admin.php'); // 执行重定向
die(); // 确保重定向后脚本停止执行,防止后续代码执行
}
// 如果用户已登录,则直接重定向到admin页面
if (isset($_SESSION['login'])) {
header('Location:admin.php');
die();
}
// 处理表单提交
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
// 验证用户名和密码,使用elseif确保逻辑严谨
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>";
}
}
?>
<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>在admin.php中,我们将不再尝试访问不存在的$username['username'],而是从会话中获取已存储的用户名。
<?php
session_start();
if(!isset($_SESSION['login'])) {
header('LOCATION:login.php'); die();
}
if(isset($_GET['logout'])){
//Simple exit message
// 确保 $_SESSION['username'] 存在再使用
$username_for_logout = isset($_SESSION['username']) ? $_SESSION['username'] : 'Guest';
$logout_message = "<div class='msgln'><span class='left-info'>User <b class='user-name-left'>". $username_for_logout ."</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
}
?>
<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 isset($_SESSION['username']) ? $_SESSION['username'] : 'Guest'; ?></b>. <a href="https://docs.google.com/document/d/1S2O4y2z_8Yu_mibQQGEU4E9pHdeckPfo5pI7FtM0YrI/edit" target="_blank">Image Dump...</a></p>
<p>Emoji's → </p>
<button id="emoji-button" style="border: none;">?</button>
<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="↑" />
</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) {
// 将 "index.php?logout=true" 修改为 "?logout=true"
window.location = "?logout=true";
}
});
});
</script>
</body>
</html>将退出链接的重定向目标改为相对路径?logout=true,使其更具通用性,并确保重定向到当前页面以触发admin.php顶部的退出逻辑。
// ... (admin.php 文件中的JavaScript代码)
$("#exit").click(function () {
var exit = confirm("Are you sure you want to leave?");
if (exit == true) {
// 将 "index.php?logout=true" 修改为 "?logout=true"
window.location = "?logout=true";
}
});
// ... (admin.php 文件中的JavaScript代码)以上就是解决PHP聊天服务登录后消息发送与用户名显示异常问题的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号