Home >Backend Development >PHP Problem >How to implement chat room ideas in php

How to implement chat room ideas in php

藏色散人
藏色散人Original
2021-09-10 10:40:232159browse

php The idea of ​​​​implementing a chat room is: 1. Create a table; 2. Set "connect.php" to connect to the database; 3. Create a user chat interface file "client.php"; 4. Implement a query to see if there is customer service Reply to the message; 5. Set up the customer service chat page "server.php"; 6. Send the message to the user.

How to implement chat room ideas in php

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

php chat room ideas

Detailed explanation of the simple implementation method of PHP chat room

The example in this article describes the simple implementation method of PHP chat room. Share it with everyone for your reference, the details are as follows:

User=> Customer Service (First put the information into the database, and then continuously query the data from the database and send it to customer service through ob long connection)

Customer Service= > User (first receive user information, then store the reply information into the database, and finally continuously request data through ajax polling, and display it to the user chat interface)

[Note:] If all pages are set up, first link to customer service Chat page (server.php), and then link to the user page (client.php)

Picture description:

Step 1: Create a table

Description: rec: the party that receives the information, sender: the party that sends the information, content: the sending content, is_new: as a mark, 1 is new information and 2 is read information (default is 1)

CREATE TABLE `chat_log` (
 `log_id` int(11) NOT NULL AUTO_INCREMENT,
 `rec` varchar(10) NOT NULL COMMENT '接受方',
 `sender` varchar(10) NOT NULL COMMENT '发送方',
 `content` text NOT NULL COMMENT '发送内容',
 `is_new` tinyint(4) NOT NULL DEFAULT '1' COMMENT '信息 1新信息 0 已读信息',
 PRIMARY KEY (`log_id`,`rec`)
) ENGINE=MyISAM AUTO_INCREMENT=105 DEFAULT CHARSET=utf8 COMMENT='用户客服聊天轮询表'

Step 2: Link to the database: connect.php

$link = mysql_connect('localhost', 'root', '');
mysql_query("set names utf8");
mysql_select_db("chat");

Step 3: User chat interface: client.php

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>User窗口</title>
  <style>
    #user {
      width: 440px;
      height: 300px;
      border: 1px solid blue;
    }
  </style>
  <script src=&#39;http://code.jquery.com/jquery-latest.js&#39;></script>
  <script>
    $(function () {
      $("#btn").click(function () {
        var content = $("textarea").val();
        if(content == &#39;&#39;){alert(&#39;发送内容不能为空&#39;);return;}
        // 发送给客服
        <!-- 把提交数据通过toServer.php存入数据库-->
        $.post("toServer.php", {&#39;msg&#39;:content}, function (res) {
          var obj = JSON.parse(res);
          $("#user").append("<b>你向客服发送:</b>" + obj + "<br>");
          $("textarea").val(" ");
        });
      });
      // 用ajax轮询方式 从数据库获取 客服是否有发送消息给用户
      var polling = {
        "url"   : &#39;fromServer.php&#39;,
        "dataType" : &#39;json&#39;,
        success  : function (res) {
          //ajax请求返回的数据
          var obj = res;
          //追加到User聊天的页面
          $("#user").append("<b style=&#39;color:red&#39;>客服回复:" + obj.content + "</b><br>");
          $.ajax(polling);
        }
      };
      $.ajax(polling); //轮询发送ajax请求
    })
  </script>
</head>
<body>
  <iframe src="" width="0" height="0" frameborder="0"></iframe>
  <h3>与客服聊天窗口</h3>
  <p contenteditable="true" id="user"></p>
  <p>
    <textarea name="msg_list" id="" cols="60" rows="15"></textarea>
    <button id="btn" type="button">send..</button>
  </p>
</body>
</html>

Fourth: The user sends information to the database and ajax polls to query whether there is customer service Reply message

toServer.php

require(&#39;connect.php&#39;);
$msg = htmlspecialchars($_POST[&#39;msg&#39;], ENT_QUOTES);
$sql = "INSERT INTO `chat_log` (rec, sender, content) VALUES(&#39;admin&#39;, &#39;user&#39;, &#39;$msg&#39; )";
mysql_query($sql, $link);
echo json_encode($msg);

fromServer.php

require(&#39;connect.php&#39;);
set_time_limit(0);//永不超时
while (true){
    $sql = "SELECT * FROM `chat_log` WHERE rec=&#39;user&#39; AND is_new=1 ORDER BY log_id DESC LIMIT 1";
    $res = mysql_query($sql, $link);
    if($row = mysql_fetch_assoc($res)){
      $sql = "UPDATE `chat_log` SET is_new=0 WHERE log_id=".$row[&#39;log_id&#39;];
      mysql_query($sql,$link);
      die(json_encode($row));
    }
}

Step 5: Customer service chat page server.php

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>客服窗口</title>
  <style>
    #server {
    width: 440px;
    height: 300px;
    border: 1px solid blue;
    }
  </style>
  <script src=&#39;http://code.jquery.com/jquery-latest.js&#39;></script>
  <!-- 进行ob缓存输出 -->
  <script>
    function showMsg(res) {
      var obj = eval(res);
      $("#server").append("<b style=&#39;color:red&#39;>User向你发送:" + obj.content + "</b><br/>");
    }
    //回复User信息
    $(function () {
      $("#btn").click(function () {
        var content = $("textarea").val();
        //客服发送的信息通过toClient.php存入数据库
        $.post("toClient.php", {&#39;msg&#39;:content},function (res) {
          var obj = JSON.parse(res);
          $("#server").append("你向User发送:" + obj+ "<br>");
          $("textarea").val("");
        })
      });
    })
  </script>
</head>
<body>
  <iframe src="./fromClient.php" width="0" height="0" frameborder="0"></iframe>
  <h3>与User聊天窗口</h3>
  <p contenteditable="true" id="server"></p>
  <p>
    <textarea name="msg_list" id="" cols="60" rows="15"></textarea>
    <button id="btn" type="button">send..</button>
  </p>
</body>
</html>

Step 6: Customer service Query the database to see if the user has sent information. Send information to the user.

fromClient.php

require(&#39;connect.php&#39;);
ob_start();       //打开一个输出缓冲区,所有的输出信息不再直接发送到浏览器,而是保存在输出缓冲区里面
echo str_repeat(&#39;&#39;, 4096);
ob_end_flush();     //发送内部缓冲区到浏览器,删除缓冲区内容,关闭缓冲区
ob_flush();       //发送内部缓冲区的内容到浏览器,删除缓冲区的内容,不关闭缓冲区
set_time_limit(0);//永不超时
while(true){
    $sql = "select * from `chat_log` where rec= &#39;admin&#39; and is_new= 1 ORDER BY log_id DESC LIMIT 1 ";
    $res = mysql_query($sql, $link);
    if($row = mysql_fetch_assoc($res)){
      $sql = "UPDATE `chat_log` SET is_new=0 where log_id=".$row[&#39;log_id&#39;];
      mysql_query($sql, $link);
      echo "<script>parent.showMsg(".json_encode($row).")</script>";
      ob_flush();
      flush();      //将ob_flush释放出来的内容,以及不在PHP缓冲区中的内容,全部输出至浏览器;刷新内部缓冲区的内容,并输出
      sleep(1);
    }
}

toClient.php

require(&#39;connect.php&#39;);
$msg = htmlspecialchars($_POST[&#39;msg&#39;], ENT_QUOTES);
if(!empty($msg)){
    $sql = "insert into chat_log(rec, sender, content) values(&#39;user&#39;, &#39;admin&#39;, &#39;$msg&#39;)";
    mysql_query($sql);
    echo json_encode($msg);
}

Here I run on the computer (server.php and client. php) chat, it was stuck at first, but after a while it got better and I started chatting normally. I’m just not sure why. If anyone knows, please tell me. I’d be very grateful!
(I understand it is caused by long connections)

[Recommended learning: "PHP Video Tutorial"]

The above is the detailed content of How to implement chat room ideas in php. For more information, please follow other related articles on the PHP Chinese website!

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