搜索
首页后端开发php教程php简略多人聊天界面的设计代码

php简单多人聊天界面的设计代码

下面来简单介绍一个最简单的登录多人聊天系统的设计,只有四个文件,分别是登录页面login.php、多人聊天界面chat.php、设计数据库操作的Sql.php文件以及注册页面regester.php,其中注册页面和登录页面的代码有%98的代码是雷同的。都是采用同样的结构。难点其实还是在Sql.php文件中,因为这个是涉及到数据库操作的文件,所以很多问题基本都是由这个页面引起的,当然还有那个多人聊天界面也是很容易出问题。总体说来其实无非就是从数据库中根据用户名和接收者的名字取出相应的对话内容。这个缺点挺大的,在实际应用中几乎是毫无用武之地的,仅仅是为了学习才会想到这样做的,对话内容放在数据库里,那也是很耗费系统资源的行为。不过保存少量的对话信息应该还是可以的。闲话就不多说了,只要能够看懂Sql.php文件的代码基本上就看懂了这整个多人聊天系统,注意我的四个文件全部都是放在一个文件下,所以当你要复制这个系统时,请务必保证这四个文件都是处于同一个文件夹下,并且最好再次确保这四个文件是用utf-8编码,如果不是请修改为UTF-8编码。要不然就会出现中文乱码现象。一个汉字在GBK编码下占用2个字符,而在UTF-8编码下占用三个字符,这一点可以用strlen()函数检验。这里要建立两个表,两个数据表如下所示:

这个表名叫comm,是专门用于存放用户对话信息的数据表:


下面的表名叫rege,是专门用于存放用户注册信息的:


下面是登录页面login.php

<span style="font-size:18px; color:#333333"><meta http-equiv="content-type" content="text/html;charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=7">
<title>welcom to login page</title>
<style type="text/css">body {	margin:auto;width:500px;background:url('table.jpg')no-repeat 200px;}div {	width:550px;padding-top:200px;	overflow:hidden;}form {    padding:3px;	border:dashed 1px green;	font-size:23px;	color:red;	background:white;}form input {	height:25px;}form span {	width:150px;height:40px;text-align:center;	display:inline-block;}form span.pic {	font-size:12px;	display:inline;}form  img{	  position: relative;	  left: 10px;	  top: 15px;	  padding-right:3px;}#show {display:inline;height:20px;margin-left:20px;font-size:12px;}#user {display:inline;font-size:14px;}#pwd {display:inline;font-size:14px;}.login {font-size:21px;align:center;display:block;height:26px;margin-left:150px;}</style>
<div>
<form action="login.php" method="post">
<span>用户名:</span><input type="text" size="20" name="user"><span id="user"></span><br><span>密码:</span><input type="text" size="20" name="pwd"><span id="pwd"></span><br><span>请输入验证码:</span><input type="text" size="10" name="check"><img  src="/static/imghwm/default1.png" data-src="tupian.php" class="lazy"   style="max-width:90%" onclick="javascript:this.+Math.random()" alt="php简略多人聊天界面的设计代码" > <span class="pic">看不清点击图片换一张</span><br><span id="show"></span><input class="login" type="submit" value="登录">
</form>
<h2 id="a-href-regester-php-点击注册-a"><a href="regester.php">点击注册</a></h2>
</div>
<?php session_id("yanzhen");	session_start();	$chars=strtolower($_SESSION['yanzhen']);//获得验证码;	if(isset($_POST['check'])){		if(trim($_POST['check'])==""){			echo "<script type=text/javascript>";			echo "document.getElementById('show').innerHTML='请输入验证码'";			echo "";exit();		}		if($chars!=trim($_POST['check'])){			echo "<script type="text/javascript">";			echo "document.getElementById('show').innerHTML='验证码输入错误'";			echo "</script>";exit();		}	}	if(isset($_POST['user'])){		//check the user name		$user=trim($_POST['user']);		if($user==""){			echo "<script type="text/javascript">";			echo "document.getElementById('user').innerHTML='用户名为空'";			echo "</script>";exit();		}		if(preg_match("/^[\x7f-\xff]+$/", $user)==0){			echo "<script type="text/javascript">";			echo "document.getElementById('user').innerHTML='用户名只允许汉字'";			echo "</script>";exit();		}		if(isset($_POST['pwd'])){			$pwd=trim($_POST['pwd']);			if(preg_match("/^[a-z0-9\-]+$/i", $pwd)==0){				echo "<script type="text/javascript">";				echo "document.getElementById('pwd').innerHTML='密码只允许数字、下划线和字母'";				echo "</script>";exit();			}			if($pwd==''){				echo "<script type="text/javascript">";				echo "document.getElementById('pwd').innerHTML='密码为空'";				echo "</script>";			}else {				include_once 'Sql.php';				$sql = new Sql();				if($sql->checkPassword($user, $pwd)){					//$_SESSION["$user"]=true;					header("location:chat.php?name=".urlencode($user));					}				else {					echo "<script type="text/javascript">";					echo "document.getElementById('show').innerHTML='{$sql->infor}'";					echo "</script>";				}			}		}	}</span>

下面是注册页面regester.php

<span style="font-size:18px; color:#333333"><meta http-equiv="content-type" content="text/html;charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=7">
<title>welcom to login page</title>
<style type="text/css">body {	margin:auto;width:500px;background:url('table.jpg')no-repeat 200px;}div {	width:550px;padding-top:200px;	overflow:hidden;}form {    padding:3px;	border:dashed 1px green;	font-size:23px;	color:red;	background:white;}form input {	height:25px;}form span {	width:150px;height:40px;text-align:center;	display:inline-block;}form span.pic {	font-size:12px;	display:inline;}form  img{	  position: relative;	  left: 10px;	  top: 15px;	  padding-right:3px;}#show {display:inline;height:20px;margin-left:20px;font-size:12px;}.login {font-size:21px;align:center;display:block;height:26px;margin-left:150px;}</style>
<div><form action="regester.php" method="post">
<span>用户名:</span><input type="text" size="20" name="user"><span id="user"></span><br><span>密码:</span><input type="text" size="20" name="pwd"><span id="pwd"></span><br><span>请输入验证码:</span><input type="text" size="10" name="check"><img  src="/static/imghwm/default1.png" data-src="tupian.php" class="lazy"   style="max-width:90%" onclick="javascript:this.+Math.random()" alt="php简略多人聊天界面的设计代码" > <span class="pic">看不清点击图片换一张</span><br><span id="show"></span><input class="login" type="submit" value="注册">
</form></div>
<?php require_once 'Sql.php';if(isset($_POST['user'])){		//check the user name		$user=trim($_POST['user']);		if($user==""){			echo "<script type=text/javascript>";			echo "document.getElementById('user').innerHTML='用户名为空'";			echo "";exit();		}		if(strlen($user)>6){			echo "<script type="text/javascript">";			echo "document.getElementById('user').innerHTML='用户名太长'";			echo "</script>";exit();		}		if(preg_match("/^[\x7f-\xff]+$/", $user)==0){			echo "<script type="text/javascript">";			echo "document.getElementById('user').innerHTML='用户名只允许汉字'";			echo "</script>";exit();		}		if(isset($_POST['pwd'])){			$pwd=trim($_POST['pwd']);			if(preg_match("/^[a-z0-9\-]+$/i", $pwd)==0){				echo "<script type="text/javascript">";				echo "document.getElementById('pwd').innerHTML='密码只允许数字、下划线和字母'";				echo "</script>";exit();			}			if($pwd==''){				echo "<script type="text/javascript">";				echo "document.getElementById('pwd').innerHTML='密码为空'";				echo "</script>";exit();			}elseif (strlen($pwd)>=19){				echo "<script type="text/javascript">";				echo "document.getElementById('pwd').innerHTML='密码长度太长'";				echo "</script>";exit();			}			else {				include_once 'Sql.php';				$sql = new Sql();				$sql->regerster($user, $pwd);			}		}	}		?></span>

下面是操作数据库的Sql.php文件

<span style="font-size:18px; color:#333333"><?phpheader ("charset=utf-8");class Sql {	protected $conn;	public $infor='';	public function __construct(){		$this->conn=mysql_connect("localhost","like","admin");		mysql_select_db("test");		if(!$this->conn)	die("fail to connect the mysql database");	}	public function queryInfor($receiver){		$arr=array();		$receiver=iconv("utf-8","gbk",$receiver);		$query="select * from `comm` where recever='$receiver' order by id desc";		mysql_query("set names gbk");		$result=mysql_query($query,$this->conn) or die("fuck error");		while($row=mysql_fetch_row($result)){			$arr[]=$row;		}		if(count($arr)>5){//保存的信息超过五条,就删除掉多余信息			for($i=count($arr)-1;$i>4;$i--){				mysql_query("delete from `comm` where id={$arr[$i][0]}") or die("fail to delete the extra information");				unset($arr[$i]);			}		}		mysql_free_result($result);		for($i=0;$i<count for return public function queryquery from where sendor="$sendor" order by id desc mysql_query names gbk>conn) or die("fuck error");		while($row=mysql_fetch_row($result)){			$arr[]=$row;		}		if(count($arr)>5){//保存的信息超过五条,就删除掉多余信息			for($i=count($arr)-1;$i>4;$i--){				mysql_query("delete from `comm` where id={$arr[$i][0]}") or die("fail to delete the extra information");				unset($arr[$i]);			}		}		mysql_free_result($result);		for($i=0;$i<count for return public function setdatabase h:i:s mysql_query names gbk>conn);		$query="insert into `comm`(sendor,time,recever,content)values('$sender','$timestamp','$receiver','$content')";		mysql_query($query,$this->conn) or die("insert error");			}	public function getSenderAll($name){		$arr= array();		$name=iconv("utf-8","gbk",$name);		$query="select user from `rege` where 1 order by id desc";		mysql_query("set names gbk",$this->conn);		$result=mysql_query($query,$this->conn) or die("no data in database");		while($row=mysql_fetch_row($result)){			$arr[]=$row[0];		}		for($i=0;$i<count return public function logout set status="0" where user="$name" mysql_query names gbk>conn) or die("注销失败");	}	public function  checkPassword($name,$password=null){		$name=iconv("utf-8","gbk",$name);		$queryP="select * from `rege` where user='$name' and password='$password' limit 1";		$queryQ="select * from `rege` where user='$name' limit 1";		mysql_query("set names gbk",$this->conn);			if($password!=null){			mysql_query($queryP,$this->conn) or die("ass error");			if(mysql_affected_rows($this->conn)>0){						$result=mysql_query("select status from `rege` where user='$name'");				$row=mysql_fetch_row($result);				if($row[0])	{					$this->infor="该用户已经登录";					return false;				}				$query="update `rege` set status=true where user='$name'";				mysql_query($query,$this->conn);				return true;				}else{				$this->infor="用户名或密码错误";				return false;			}		}		else {			mysql_query($queryQ,$this->conn) or die("sorry error");			if(mysql_affected_rows($this->conn)>0){				$this->infor="该用户名已被注册";				return false;			}			return true;		}	}	public function regerster($name,$pwd){		$name=iconv("utf-8","gbk",$name);		$query="INSERT INTO `rege`(`user`,`password`) VALUES ('$name','$pwd')";		mysql_query("set names gbk",$this->conn);		mysql_query($query,$this->conn) or die("注册失败");		$this->infor="注册成功";	}	public function close(){		mysql_close($this->conn);	}}</count></count></count></span>

下面是用户登录之后的多人聊天界面chat.php,说是多人聊天,其实是很粗糙的界面,就是一个ul标签列出了所有人传达给你的最新五条信息,多余信息会被自动删除,然后你可以选择任意一个人写下对他/她说的话,然后就是刷新显示。其实原理挺简单的。

<span style="font-size:18px; color:#333333"><?php require_once 'Sql.php';	session_id("yanzhen");	session_start();	if(isset($_GET['id'])&&isset($_GET['log'])){		if($_GET['id']==1){			$og= new Sql();			$sess_name=urldecode($_GET['log']);			$og->logout($sess_name);			$_SESSION["$sess_name"]=false;			header("content-type=text/html;charset=utf-8");			echo "注销成功";			echo "<a href="login.php">返回到登录页面</a>";			exit();		}	}		if(isset($_GET['name'])){		$user=urldecode($_GET['name']);		$user=$_GET['name'];	}	else{		header("location:login.php");		}	if(isset($_POST['content'])){		$tmp_content=$_POST['content'];		$tmp_user=$_POST['user'];		$tmp_receive=$_POST['selec'];		$tmp=new Sql();		$tmp->setDatabase($tmp_user, $tmp_receive, $tmp_content);		$tmp=$tmp_content=$tmp_user=$tmp_receive=null;	}?><meta http-equiv="content-type" content="text/html;charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=7">
<title>welcom to chat page</title>
<style type="text/css">#area {margin:auto;width:500px;color:red;background-color:grey;}#area ul li{height:20px;list-style-type:none;}form {margin:auto;width:500px;height:35px;color:white;   background-color:black;}h3 {padding-left:200px;}   </style>
<h3 id="a-href-chat-php-id-amp-log-lt-php-echo-urlencode-user-gt-注销-a"><a href="chat.php?id=1&log=<?php%20echo%20urlencode(%24user);?>">注销</a></h3>
<div id="area"><ul>
<?php $sql= new Sql();	$arr=array();	$arr=$sql->queryInfor($user);	for($i=count($arr)-1;$i>=0;$i--){		echo "<li>".$arr[$i][1]."在"					.$arr[$i][2]."对你说过:</li>
<br>";		echo "<li>".$arr[$i][4]."</li>
<br>";	}	$arr=$sql->queryQuery($user);	for($i=count($arr)-1;$i>=0;$i--){		echo "<li style="text-align:right;color:green">"."你在".$arr[$i][2]."对"		.$arr[$i][3]."说过:</li>
<br>";		echo "<li style="text-align:right;color:green">".$arr[$i][4]."</li>
<br>";	}?></ul></div>
<form action="chat.php?name=<?php%20echo%20urlencode(%24user);?>" method="post">
<input type="hidden" name="user" value="<?php echo $user; ?>"><?php echo $user;?>想对<select name="selec"><?php $arr=$sql->getSenderAll($user);	for($i=0;$i<count if echo value='\"$arr[$i]\"'>$arr[$i]";	}?></count></select>说:<input name="content" type="text" size="30" maxlength="30/"><input type="submit" value="发送">
</form>
<?php //show the information when chatting?></span>

聊天界面图:




声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
使用数据库存储会话的优点是什么?使用数据库存储会话的优点是什么?Apr 24, 2025 am 12:16 AM

使用数据库存储会话的主要优势包括持久性、可扩展性和安全性。1.持久性:即使服务器重启,会话数据也能保持不变。2.可扩展性:适用于分布式系统,确保会话数据在多服务器间同步。3.安全性:数据库提供加密存储,保护敏感信息。

您如何在PHP中实现自定义会话处理?您如何在PHP中实现自定义会话处理?Apr 24, 2025 am 12:16 AM

在PHP中实现自定义会话处理可以通过实现SessionHandlerInterface接口来完成。具体步骤包括:1)创建实现SessionHandlerInterface的类,如CustomSessionHandler;2)重写接口中的方法(如open,close,read,write,destroy,gc)来定义会话数据的生命周期和存储方式;3)在PHP脚本中注册自定义会话处理器并启动会话。这样可以将数据存储在MySQL、Redis等介质中,提升性能、安全性和可扩展性。

什么是会话ID?什么是会话ID?Apr 24, 2025 am 12:13 AM

SessionID是网络应用程序中用来跟踪用户会话状态的机制。1.它是一个随机生成的字符串,用于在用户与服务器之间的多次交互中保持用户的身份信息。2.服务器生成并通过cookie或URL参数发送给客户端,帮助在用户的多次请求中识别和关联这些请求。3.生成通常使用随机算法保证唯一性和不可预测性。4.在实际开发中,可以使用内存数据库如Redis来存储session数据,提升性能和安全性。

您如何在无状态环境(例如API)中处理会议?您如何在无状态环境(例如API)中处理会议?Apr 24, 2025 am 12:12 AM

在无状态环境如API中管理会话可以通过使用JWT或cookies来实现。1.JWT适合无状态和可扩展性,但大数据时体积大。2.Cookies更传统且易实现,但需谨慎配置以确保安全性。

您如何防止与会议有关的跨站点脚本(XSS)攻击?您如何防止与会议有关的跨站点脚本(XSS)攻击?Apr 23, 2025 am 12:16 AM

要保护应用免受与会话相关的XSS攻击,需采取以下措施:1.设置HttpOnly和Secure标志保护会话cookie。2.对所有用户输入进行输出编码。3.实施内容安全策略(CSP)限制脚本来源。通过这些策略,可以有效防护会话相关的XSS攻击,确保用户数据安全。

您如何优化PHP会话性能?您如何优化PHP会话性能?Apr 23, 2025 am 12:13 AM

优化PHP会话性能的方法包括:1.延迟会话启动,2.使用数据库存储会话,3.压缩会话数据,4.管理会话生命周期,5.实现会话共享。这些策略能显着提升应用在高并发环境下的效率。

什么是session.gc_maxlifetime配置设置?什么是session.gc_maxlifetime配置设置?Apr 23, 2025 am 12:10 AM

thesession.gc_maxlifetimesettinginphpdeterminesthelifespanofsessiondata,setInSeconds.1)它'sconfiguredinphp.iniorviaini_set().2)abalanceIsiseededeedeedeedeedeedeedto to to avoidperformance andununununununexpectedLogOgouts.3)

您如何在PHP中配置会话名?您如何在PHP中配置会话名?Apr 23, 2025 am 12:08 AM

在PHP中,可以使用session_name()函数配置会话名称。具体步骤如下:1.使用session_name()函数设置会话名称,例如session_name("my_session")。2.在设置会话名称后,调用session_start()启动会话。配置会话名称可以避免多应用间的会话数据冲突,并增强安全性,但需注意会话名称的唯一性、安全性、长度和设置时机。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境