首頁  >  文章  >  後端開發  >  php怎麼實作聊天工具

php怎麼實作聊天工具

藏色散人
藏色散人原創
2021-11-23 09:58:042749瀏覽

php實作聊天工具的方法:1、執行函數set_chat_msg;2、在伺服器中執行chat_send_ajax.php;3、從Query String接收表單資料;4、收集聊天資訊;5、在視窗返回內容即可。

php怎麼實作聊天工具

本文操作環境:Windows7系統、PHP7.1、Dell G3電腦。

php怎麼實作聊天工具?

PHP實作最簡單的聊天室應用程式

#介紹

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

核心邏輯

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

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聊天應用程式。創建該應用程式的邏輯也非常簡單。即使是初學者理解起來也不會有任何困難。

許可證

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

來源:http://www.codeceo.com/article/php-chart-app.html

推薦學習:《PHP影片教學

以上是php怎麼實作聊天工具的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn