PHP實現最簡單的聊天室應用_PHP教程

來源:互聯網
上載者:User

PHP實現最簡單的聊天室應用


介紹

聊天應用程式在網上非常常見。開發人員在構建這類應用程式時的選擇也很多。這篇文章介紹了如何?基於PHP-AJAX的聊天應用程式,並且不需要重新整理頁面就可以發送和接收訊息。

核心邏輯

在定義應用程式的核心功能之前,先來看一看聊天應用程式的基本外觀,如以下所示:

通過聊天視窗底部的輸入框輸入聊天文本。點擊Send按鈕,就開始執行函數set_chat_msg。這是一個基於Ajax的函數,因此無需重新整理頁面就可以將聊天文本發送到伺服器。程式在伺服器中執行chat_send_ajax.php以及使用者名稱和聊天文本。

 
  1. //
  2. // Set Chat Message
  3. //
  4. function set_chat_msg()
  5. {
  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. var url = "chat_send_ajax.php";
  20. var strname="noname";
  21. var strmsg="";
  22. if (document.getElementById("txtname") != null)
  23. {
  24. strname = document.getElementById("txtname").value;
  25. document.getElementById("txtname").readOnly=true;
  26. }
  27. if (document.getElementById("txtmsg") != null)
  28. {
  29. strmsg = document.getElementById("txtmsg").value;
  30. document.getElementById("txtmsg").value = "";
  31. }
  32. url += "?name=" + strname + "&msg=" + strmsg;
  33. oxmlHttpSend.open("GET",url,true);
  34. oxmlHttpSend.send(null);
  35. }

PHP模組從Query String查詢字串)中接收表單資料,更新到命名為chat的資料庫表中。chat資料庫表有命名為IDUSERNAMECHATDATEMSG的列。ID欄位是自動遞增欄位,所以這個ID欄位的賦值將自動遞增。當前的日期和時間,會更新到CHATDATE列。

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

為了接收來自資料庫表中所有使用者的聊天訊息,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函數。

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

在chat_recv_ajax.php程式中,來自於使用者的聊天訊息會通過SQL select命令進行收集。為了限制行數,在SQL查詢中還給出了限制子句limit 200),即要求聊天資料庫表中的最後200行。所獲得的訊息再返回給Ajax函數,用於在聊天視窗中顯示內容。

 
  1. require_once('dbconnect.php');
  2. db_connect();
  3. $sql = "SELECT *, date_format(chatdate,'%d-%m-%Y %r')
  4. as cdt from chat order by ID desc limit 200";
  5. $sql = "SELECT * FROM (" . $sql . ") as ch order by ID";
  6. $result = mysql_query($sql) or die('Query failed: ' . mysql_error());
  7. // Update Row Information
  8. $msg="";
  9. while ($line = mysql_fetch_array($result, MYSQL_ASSOC))
  10. {
  11. $msg = $msg . "" .
  12. "" .
  13. "";
  14. }
  15. $msg=$msg . "
  16. "font-size: 10pt;" border="0">
  17. " . $line["cdt"] .
  18. "
  19. " . $line["username"] .
  20. ":
  21. " . $line["msg"] .
  22. "
  23. ";
  24. echo $msg;
  25. 資料準備就緒的同時,JavaScript函數會收集來自於PHP接收到的資料。這些資料將被安排置於DIV標籤內。oxmlHttp.responseText會保留從PHP程式接收到的聊天訊息,並複製到DIV標籤的document.getElementById(“DIV_CHAT”).innerHTML 屬性。
  26. function get_chat_msg_result(t)
  27. {
  28. if(oxmlHttp.readyState==4 || oxmlHttp.readyState=="complete")
  29. {
  30. if (document.getElementById("DIV_CHAT") != null)
  31. {
  32. document.getElementById("DIV_CHAT").innerHTML = oxmlHttp.responseText;
  33. oxmlHttp = null;
  34. }
  35. var scrollDiv = document.getElementById("DIV_CHAT");
  36. scrollDiv.scrollTop = scrollDiv.scrollHeight;
  37. }
  38. }

下面的SQL CREATE TABLE命令可用於建立名為chat的資料庫表。所有由使用者輸入的資訊都會進入到資料庫表中。

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

興趣點

這段用於實現聊天應用程式的代碼非常有意思。它可以改進成為一個完全成熟的HTTP聊天應用程式。建立該應用程式的邏輯也非常簡單。即使是初學者理解起來也不會有任何困難。

許可證

這篇文章,以及任何相關的原始碼和檔案,都獲得了The Code Project Open License (CPOL)的許可。

譯文連結:http://www.codeceo.com/article/php-chart-app.html
英文原文:Chat Application in PHP

http://www.bkjia.com/PHPjc/1027371.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/1027371.htmlTechArticlePHP實現最簡單的聊天室應用 介紹 聊天應用程式在網上非常常見。開發人員在構建這類應用程式時的選擇也很多。這篇文章介紹了如何?...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.