Home > Article > Backend Development > PHP chat room technology
This article mainly introduces the simple implementation method of PHP chat room. It analyzes the database operation and ajax interaction related to PHP chat room in detail in the form of examples. Friends in need can refer to it
The examples in this article describe the simple implementation of PHP chat room. method. Share it with everyone for your reference, the details are as follows:
User => Customer Service (first store the information in the database, and then continuously query the data from the database and send it to the customer service through ob+ long connection)
Customer Service => User (first receive the user information , then store the reply information into the database, and finally continuously request data through ajax polling, and display it to the user chat interface)
[Note:] If all pages are set up, first link to the customer service chat page (server.php), and then link to the user Page (client.php)
Picture description:
Step 1: Create a table
Instructions: rec: the party that receives the information, sender: the party that sends the information, content: the sending content, is_new: as a mark, 1 is new information 2 is the read information (default is 1)
CREATE TABLE `chat_log` ( `log_id` int(11) NOT NULL AUTO_INCREMENT, `rec` varchar(10) NOT NULL COMMENT '接受方', `sender` varchar(10) NOT NULL COMMENT '发送方', `content` text NOT NULL COMMENT '发送内容', `is_new` tinyint(4) NOT NULL DEFAULT '1' COMMENT '信息 1新信息 0 已读信息', PRIMARY KEY (`log_id`,`rec`) ) ENGINE=MyISAM AUTO_INCREMENT=105 DEFAULT CHARSET=utf8 COMMENT='用户客服聊天轮询表'
Step 2: Link to the database: connect.php
$link = mysql_connect('localhost', 'root', ''); mysql_query("set names utf8"); mysql_select_db("chat");
Step 3: User chat interface: client.php
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>User窗口</title> <style> #user { width: 440px; height: 300px; border: 1px solid blue; } </style> <script src='http://code.jquery.com/jquery-latest.js'></script> <script> $(function () { $("#btn")。click(function () { var content = $("textarea")。val(); if(content == ''){alert('发送内容不能为空');return;} // 发送给客服 <!-- 把提交数据通过toServer.php存入数据库--> $.post("toServer.php", {'msg':content}, function (res) { var obj = JSON.parse(res); $("#user")。append("<b>你向客服发送:</b>" + obj + "<br>"); $("textarea")。val(" "); }); }); // 用ajax轮询方式 从数据库获取 客服是否有发送消息给用户 var polling = { "url" : 'fromServer.php', "dataType" : 'json', success : function (res) { //ajax请求返回的数据 var obj = res; //追加到User聊天的页面 $("#user")。append("<b style='color:red'>客服回复:" + obj.content + "</b><br>"); $.ajax(polling); } }; $.ajax(polling); //轮询发送ajax请求 }) </script> </head> <body> <iframe src="" width="0" height="0" frameborder="0"></iframe> <h3>与客服聊天窗口</h3> <div contenteditable="true" id="user"></div> <div> <textarea name="msg_list" id="" cols="60" rows="15"></textarea> <button id="btn" type="button">send</button> </div> </body> </html>
Fourth: User sends information into the database + ajax Polling to check if there is any customer service reply message
toServer.php require('connect.php'); $msg = htmlspecialchars($_POST['msg'], ENT_QUOTES); $sql = "INSERT INTO `chat_log` (rec, sender, content) VALUES('admin', 'user', '$msg' )"; mysql_query($sql, $link); echo json_encode($msg); fromServer.php require('connect.php'); set_time_limit(0);//永不超时 while (true){ $sql = "SELECT * FROM `chat_log` WHERE rec='user' AND is_new=1 ORDER BY log_id DESC LIMIT 1"; $res = mysql_query($sql, $link); if($row = mysql_fetch_assoc($res)){ $sql = "UPDATE `chat_log` SET is_new=0 WHERE log_id=".$row['log_id']; mysql_query($sql,$link); die(json_encode($row)); } }
Step 5: Customer service chat page server.php
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>客服窗口</title> <style> #server { width: 440px; height: 300px; border: 1px solid blue; } </style> <script src='http://code.jquery.com/jquery-latest.js'></script> <!-- 进行ob缓存输出 --> <script> function showMsg(res) { var obj = eval(res); $("#server")。append("<b style='color:red'>User向你发送:" + obj.content + "</b><br/>"); } //回复User信息 $(function () { $("#btn")。click(function () { var content = $("textarea")。val(); //客服发送的信息通过toClient.php存入数据库 $.post("toClient.php", {'msg':content},function (res) { var obj = JSON.parse(res); $("#server")。append("你向User发送:" + obj+ "<br>"); $("textarea")。val(""); }) }); }) </script> </head> <body> <iframe src="./fromClient.php" width="0" height="0" frameborder="0"></iframe> <h3>与User聊天窗口</h3> <div contenteditable="true" id="server"></div> <div> <textarea name="msg_list" id="" cols="60" rows="15"></textarea> <button id="btn" type="button">send</button> </div> </body> </html>
Step 6: Customer service query database to see if the user has sent information + Send information to the user
fromClient.php require('connect.php'); ob_start(); //打开一个输出缓冲区,所有的输出信息不再直接发送到浏览器,而是保存在输出缓冲区里面 echo str_repeat('', 4096); ob_end_flush(); //发送内部缓冲区到浏览器,删除缓冲区内容,关闭缓冲区 ob_flush(); //发送内部缓冲区的内容到浏览器,删除缓冲区的内容,不关闭缓冲区 set_time_limit(0);//永不超时 while(true){ $sql = "select * from `chat_log` where rec= 'admin' and is_new= 1 ORDER BY log_id DESC LIMIT 1 "; $res = mysql_query($sql, $link); if($row = mysql_fetch_assoc($res)){ $sql = "UPDATE `chat_log` SET is_new=0 where log_id=".$row['log_id']; mysql_query($sql, $link); echo "<script>parent.showMsg(".json_encode($row)。")</script>"; ob_flush(); flush(); //将ob_flush释放出来的内容,以及不在PHP缓冲区中的内容,全部输出至浏览器;刷新内部缓冲区的内容,并输出 sleep(1); } } toClient.php require('connect.php'); $msg = htmlspecialchars($_POST['msg'], ENT_QUOTES); if(!empty($msg)){ $sql = "insert into chat_log(rec, sender, content) values('user', 'admin', '$msg')"; mysql_query($sql); echo json_encode($msg); }
Here I am running on the computer (server.php and client.php) When chatting, it was stuck at first. After a while, it got better and chatted normally. I just don’t know the reason. If anyone knows, please tell me. Thank you very much!