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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio
