search
HomeBackend DevelopmentPHP Tutorialphp实现简易聊天室应用代码_PHP

核心逻辑

在定义应用程序的核心功能之前,先来看一看聊天应用程序的基本外观,如以下截图所示:

通过聊天窗口底部的输入框输入聊天文本。点击Send按钮,就开始执行函数set_chat_msg。这是一个基于Ajax的函数,因此无需刷新页面就可以将聊天文本发送到服务器。程序在服务器中执行chat_send_ajax.php以及用户名和聊天文本。

// 
// Set Chat Message 
// 
 
function set_chat_msg() 
{ 
  if(typeof XMLHttpRequest != "undefined") 
  { 
    oxmlHttpSend = new XMLHttpRequest(); 
  } 
  else if (window.ActiveXObject) 
  { 
    oxmlHttpSend = new ActiveXObject("Microsoft.XMLHttp"); 
  } 
  if(oxmlHttpSend == null) 
  { 
    alert("Browser does not support XML Http Request"); 
    return; 
  } 
 
  var url = "chat_send_ajax.php"; 
  var strname="noname"; 
  var strmsg=""; 
  if (document.getElementById("txtname") != null) 
  { 
    strname = document.getElementById("txtname").value; 
    document.getElementById("txtname").readOnly=true; 
  } 
  if (document.getElementById("txtmsg") != null) 
  { 
    strmsg = document.getElementById("txtmsg").value; 
    document.getElementById("txtmsg").value = ""; 
  } 
 
  url += "?name=" + strname + "&msg=" + strmsg; 
  oxmlHttpSend.open("GET",url,true); 
  oxmlHttpSend.send(null); 
} 

PHP模块从Query String(查询字符串)中接收表单数据,更新到命名为chat的数据库表中。chat数据库表有命名为ID、USERNAME、CHATDATE和MSG的列。ID字段是自动递增字段,所以这个ID字段的赋值将自动递增。当前的日期和时间,会更新到CHATDATE列。

require_once('dbconnect.php'); 
 
db_connect(); 
 
$msg = $_GET["msg"]; 
$dt = date("Y-m-d H:i:s"); 
$user = $_GET["name"]; 
 
$sql="INSERT INTO chat(USERNAME,CHATDATE,MSG) " . 
   "values(" . quote($user) . "," . 
   quote($dt) . "," . quote($msg) . ");"; 
 
   echo $sql; 
 
$result = mysql_query($sql); 
if(!$result) 
{ 
  throw new Exception('Query failed: ' . mysql_error()); 
  exit(); 
} 

为了接收来自数据库表中所有用户的聊天消息,timer函数被设置为循环5秒调用以下的JavaScript命令,即每隔5秒时间执行get_chat_msg函数。

var t = setInterval(function(){get_chat_msg()},5000);

get_chat_msg是一个基于Ajax的函数。它执行chat_recv_ajax.php程序以获得来自于数据库表的聊天信息。在 onreadystatechange属性中,另一个JavaScript 函数get_chat_msg_result被连接起来。在返回来自于数据库表中的聊天消息的同时,程序控制进入到 get_chat_msg_result函数。

// 
// General Ajax Call 
// 
 
var oxmlHttp; 
var oxmlHttpSend; 
 
function get_chat_msg() 
{ 
  if(typeof XMLHttpRequest != "undefined") 
  { 
    oxmlHttp = new XMLHttpRequest(); 
  } 
  else if (window.ActiveXObject) 
  { 
    oxmlHttp = new ActiveXObject("Microsoft.XMLHttp"); 
  } 
  if(oxmlHttp == null) 
  { 
    alert("Browser does not support XML Http Request"); 
    return; 
  } 
 
  oxmlHttp.onreadystatechange = get_chat_msg_result; 
  oxmlHttp.open("GET","chat_recv_ajax.php",true); 
  oxmlHttp.send(null); 
} 

在chat_recv_ajax.php程序中,来自于用户的聊天消息会通过SQL select命令进行收集。为了限制行数,在SQL查询中还给出了限制子句(limit 200),即要求聊天数据库表中的最后200行。所获得的消息再返回给Ajax函数,用于在聊天窗口中显示内容。

require_once('dbconnect.php'); 
 
db_connect(); 
 
$sql = "SELECT *, date_format(chatdate,'%d-%m-%Y %r') 
as cdt from chat order by ID desc limit 200"; 
$sql = "SELECT * FROM (" . $sql . ") as ch order by ID"; 
$result = mysql_query($sql) or die('Query failed: ' . mysql_error()); 
 
// Update Row Information 
$msg=""; 
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) 
{ 
  $msg = $msg . "" . 
    "" . 
    ""; 
} 
$msg=$msg . "<table style="color: blue; font-family: verdana, arial; " . 
 "font-size: 10pt;" border="0"> 
 <tbody><tr><td>" . $line["cdt"] . 
 " </td><td>" . $line["username"] . 
 ": </td><td>" . $line["msg"] . 
 "</td></tr></tbody></table>"; 
 
echo $msg; 
 
数据准备就绪的同时,JavaScript函数会收集来自于PHP接收到的数据。这些数据将被安排置于DIV标签内。oxmlHttp.responseText会保留从PHP程序接收到的聊天消息,并复制到DIV标签的document.getElementById(“DIV_CHAT”).innerHTML属性。 
 
function get_chat_msg_result(t) 
{ 
  if(oxmlHttp.readyState==4 || oxmlHttp.readyState=="complete") 
  { 
    if (document.getElementById("DIV_CHAT") != null) 
    { 
      document.getElementById("DIV_CHAT").innerHTML = oxmlHttp.responseText; 
      oxmlHttp = null; 
    } 
    var scrollDiv = document.getElementById("DIV_CHAT"); 
    scrollDiv.scrollTop = scrollDiv.scrollHeight; 
  } 
} 

下面的SQL CREATE TABLE命令可用于创建名为chat的数据库表。所有由用户输入的信息都会进入到数据库表中。

create table chat( id bigint AUTO_INCREMENT,username varchar(20),
chatdate datetime,msg varchar(500), primary key(id));

这段用于实现聊天应用程序的代码非常有意思,它可以改进成为一个完全成熟的HTTP聊天应用程序,创建该应用程序的逻辑也非常简单,即使是初学者理解起来也不会有任何困难,希望这篇文章对大家的学习有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

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

Introduction to the Instagram APIIntroduction to the Instagram APIMar 02, 2025 am 09:32 AM

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

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

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-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

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

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

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' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

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.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

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

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!