Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement chat tools with php

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Editor to share with you how to achieve php chat tools, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to understand it!

The method of php to achieve chat tools: 1, execute the function set_chat_msg;2, execute chat_send_ajax.php;3 in the server, receive form data from Query String; 4, collect chat information; 5, return the content in the window.

Implementing the simplest chat room application with PHP

Introduction

Chat applications are very common on the Internet. Developers also have a lot of options when building such applications. This article describes how to implement a PHP-AJAX-based chat application and send and receive messages without refreshing the page.

Core logic

Before defining the core functionality of the application, take a look at the basic appearance of the chat application, as shown in the following screenshot:

Enter the chat text through the input box at the bottom of the chat window. Click the Send button to execute the function set_chat_msg. This is an Ajax-based function, so you can send chat text to the server without refreshing the page. The program executes chat_send_ajax.php in the server as well as user name and chat text.

/ 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 XMLHttpRequest"); 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);}

The PHP module receives form data from Query String (query string) and updates it to a database table named chat. The chat database table has columns named ID, USERNAME, CHATDATE, and MSG. The ID field is automatically incremented, so the assignment to this ID field will be incremented automatically. The current date and time are updated to the CHATDATE column.

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 ();}

In order to receive chat messages from all users in the database table, the timer function is set to call the following JavaScript command in a loop of 5 seconds, that is, to execute the get_chat_msg function every 5 seconds.

Var t = setInterval (function () {get_chat_msg ()}, 5000)

Get_chat_msg is a function based on Ajax. It executes the chat_recv_ajax.php program to get chat information from the database table. In the onreadystatechange property, another JavaScript function, get_chat_msg_result, is concatenated. While returning chat messages from the database table, the program controls to enter the get_chat_msg_result function.

/ 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 XMLHttpRequest"); return } oxmlHttp.onreadystatechange = get_chat_msg_result; oxmlHttp.open ("GET", "chat_recv_ajax.php", true); oxmlHttp.send (null);}

In the chat_recv_ajax.php program, chat messages from users are collected through the SQL select command. To limit the number of rows, a restriction clause (limit 200) is also given in the SQL query, which requires the last 200 rows in the chat database table. The obtained message is returned to the Ajax function, which is used to display the content in the chat window.

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. "". $line ["cdt"]. "". $line ["username"]. ":" $line ["msg"]. ""; echo $msg

When the data is ready, the JavaScript function collects the data received from the PHP. This data will be arranged in the DIV tag. OxmlHttp.responseText retains the chat messages received from the PHP program and copies them to the document.getElementById ("DIV_CHAT") [xss_clean] attribute of the DIV tag.

Function get_chat_msg_result (t) {if (oxmlHttp.readyState==4 | | oxmlHttp.readyState== "complete") {if (document.getElementById ("DIV_CHAT")! = null) {document.getElementById ("DIV_CHAT") [xss_clean] = oxmlHttp.responseText; oxmlHttp = null;} var scrollDiv = document.getElementById ("DIV_CHAT"); scrollDiv.scrollTop = scrollDiv.scrollHeight;}}

The following SQL CREATE TABLE command can be used to create a database table named chat. All the information entered by the user goes into the database table.

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

Point of interest

This code for implementing a chat application is very interesting. It can be improved into a full-fledged HTTP chat application. The logic for creating the application is also very simple. There will be no difficulty even for beginners to understand.

License

This article, as well as any related source code and files, is licensed by The Code Project Open License (CPOL).

The above is all the contents of the article "how to implement chat tools in php". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report