PHP implements the simplest chat room Application

Source: Internet
Author: User

PHP implements the simplest chat room Application

Introduction

Chat applications are very common online. Developers also have many choices when building such applications. This article describes how to implement a PHP-AJAX-based chat application that can send and receive messages without refreshing the page.

Core Logic

Before defining the core functions of an application, let's take a look at the basic appearance of the chat application, as shown below:

Enter the chat text in the text box at the bottom of the chat window. Click the Send button to start executing the set_chat_msg function. This is an Ajax-based function, so you can send chat text to the server without refreshing the page. The program runs chat_send_ajax.php and the user name and chat text on the server.

 
 
  1. // 
  2. // Set Chat Message 
  3. // 
  4.  
  5. function set_chat_msg() 
  6.     if(typeof XMLHttpRequest != "undefined") 
  7.     { 
  8.         oxmlHttpSend = new XMLHttpRequest(); 
  9.     } 
  10.     else if (window.ActiveXObject) 
  11.     { 
  12.        oxmlHttpSend = new ActiveXObject("Microsoft.XMLHttp"); 
  13.     } 
  14.     if(oxmlHttpSend == null) 
  15.     { 
  16.        alert("Browser does not support XML Http Request"); 
  17.        return; 
  18.     } 
  19.  
  20.     var url = "chat_send_ajax.php"; 
  21.     var strname="noname"; 
  22.     var strmsg=""; 
  23.     if (document.getElementById("txtname") != null) 
  24.     { 
  25.         strname = document.getElementById("txtname").value; 
  26.         document.getElementById("txtname").readOnly=true; 
  27.     } 
  28.     if (document.getElementById("txtmsg") != null) 
  29.     { 
  30.         strmsg = document.getElementById("txtmsg").value; 
  31.         document.getElementById("txtmsg").value = ""; 
  32.     } 
  33.  
  34.     url += "?name=" + strname + "&msg=" + strmsg; 
  35.     oxmlHttpSend.open("GET",url,true); 
  36.     oxmlHttpSend.send(null); 

The PHP module receives form data from the Query String and updates it to the database table named "chat. The chat database table is namedID,USERNAME,CHATDATEAndMSG. The ID field is auto-incrementing, so the value assignment of this ID field is auto-incrementing. The current date and time are updated to the CHATDATE column.

 
 
  1. require_once('dbconnect.php'); 
  2.  
  3. db_connect(); 
  4.  
  5. $msg = $_GET["msg"]; 
  6. $dt = date("Y-m-d H:i:s"); 
  7. $user = $_GET["name"]; 
  8.  
  9. $sql="INSERT INTO chat(USERNAME,CHATDATE,MSG) " . 
  10.       "values(" . quote($user) . "," . 
  11.       quote($dt) . "," . quote($msg) . ");"; 
  12.  
  13.       echo $sql; 
  14.  
  15. $result = mysql_query($sql); 
  16. if(!$result) 
  17.     throw new Exception('Query failed: ' . mysql_error()); 
  18.     exit(); 

To receive chat messages from all users in the database table, the timer function is set to call the following JavaScript commands in a 5-second cycle, that is, the get_chat_msg function is executed every 5 seconds.

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

Get_chat_msg is an Ajax-based function. It executes the chat_recv_ajax.php program to obtain chat information from the database table. In the onreadystatechange attribute, another JavaScript function get_chat_msg_result is connected. When a chat message from a database table is returned, the program control enters the get_chat_msg_result function.

 
 
  1. // 
  2. // General Ajax Call 
  3. // 
  4.  
  5. var oxmlHttp; 
  6. var oxmlHttpSend; 
  7.  
  8. function get_chat_msg() 
  9.     if(typeof XMLHttpRequest != "undefined") 
  10.     { 
  11.         oxmlHttp = new XMLHttpRequest(); 
  12.     } 
  13.     else if (window.ActiveXObject) 
  14.     { 
  15.        oxmlHttp = new ActiveXObject("Microsoft.XMLHttp"); 
  16.     } 
  17.     if(oxmlHttp == null) 
  18.     { 
  19.         alert("Browser does not support XML Http Request"); 
  20.        return; 
  21.     } 
  22.  
  23.     oxmlHttp.onreadystatechange = get_chat_msg_result; 
  24.     oxmlHttp.open("GET","chat_recv_ajax.php",true); 
  25.     oxmlHttp.send(null); 

In the chat_recv_ajax.php programselectCommand to collect. To limit the number of rows, the limit clause limit 200 is also provided in the SQL query, that is, the last 200 rows in the chat database table are required. The obtained message is returned to the Ajax function, which is used to display the content in the chat window.

 
 
  1. Require_once ('dbconnect. php ');
  2.  
  3. Db_connect ();
  4.  
  5. $ SQL = "SELECT *, date_format (chatdate, '% d-% m-% Y % R ')
  6. As cdt from chat order by ID desc limit 200 ";
  7. $ SQL = "SELECT * FROM (". $ SQL. ") as ch order by ID ";
  8. $ Result = mysql_query ($ SQL) or die ('query failed: '. mysql_error ());
  9.  
  10. // Update Row Information
  11. $ Msg = "";
  12. While ($ line = mysql_fetch_array ($ result, MYSQL_ASSOC ))
  13. {
  14. $ Msg = $ msg ."".
  15. "".
  16. "";
  17. }
  18. $ Msg = $ msg. "<table style =" color: blue; font-family: verdana, arial ;".
  19. "Font-size: 10pt;" border = "0">
  20. <Tbody> <tr> <td> ". $ line [" cdt "].
  21. "</Td> <td>". $ line ["username"].
  22. ": </Td> <td>". $ line ["msg"].
  23. "</Td> </tr> </tbody> </table> ";
  24.  
  25. Echo $ msg;
  26.  
  27. When data is ready, JavaScript Functions collect data received by PHP. The data will be placed in the DIV label. OxmlHttp. responseText retains the chat messages received from the PHP program and copies them to the document. getElementById ("DIV_CHAT"). innerHTML attribute of the DIV tag.
  28.  
  29. Function get_chat_msg_result (t)
  30. {
  31. If (oxmlHttp. readyState = 4 | oxmlHttp. readyState = "complete ")
  32. {
  33. If (document. getElementById ("DIV_CHAT ")! = Null)
  34. {
  35. Document. getElementById ("DIV_CHAT"). innerHTML = oxmlHttp. responseText;
  36. OxmlHttp = null;
  37. }
  38. Var scrollDiv = document. getElementById ("DIV_CHAT ");
  39. ScrollDiv. scrollTop = scrollDiv. scrollHeight;
  40. }
  41. }

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

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

Point of interest

The code used to implement the chat application is very interesting. It can be improved into a completely mature HTTP chat application. The logic for creating this application is also very simple. Even beginners do not have any difficulties.

License

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

Http://www.codeceo.com/article/php-chart-app.html.
Chat Application in PHP

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.