Easy Code Share > PHP > How to Create Many Web Chat Rooms Using PHP, JS

How to Create Many Web Chat Rooms Using PHP, JS


Let us investigate how a web chat room in PHP and JS is working in a simple way. In addition, if people require many web chat rooms, how do you let the attendee create more meeting places according to distinct topics. We extend the previous post about a single chat room with unlimited attendees to make the solution more flexible.

All codes here are not complicated, so you can easily understand even though you are still students in school. To benefit your learning, we will provide you download link to a zip file thus you can get all source codes for future usage.

Estimated reading time: 10 minutes

 

 

BONUS
Source Code Download

We have released it under the MIT license, so feel free to use it in your own project or your school homework.

 

Download Guideline

  • Prepare HTTP server such as XAMPP or WAMP in your windows environment.
  • Download and unzip into a folder that http server can access.
 DOWNLOAD SOURCE

 

SECTION 1
Multiple Chat Rooms

The example extened from the previous one allows users to create a new room, instead of only the default room. Let us loot at how to manage many web chat rooms in PHP and JS.

 

Client-Server View

We design web chat rooms and interpret the system from client-server aspect. The web chat implemented in PHP and JS is available in our previous post, and will be extend to many web chat rooms here. Each web chat room stores data in a log file, independently.

The well-known HTTP service Apache always pre-forks child processes to listen incoming chat sessions from browsers. Chat sessions are in a form of AJAX request. Each Apache child process serves a chat request by updating chat contents in a log file, and then reply to browser clients with the whole contents.

Many Chat Rooms from Client-Server View

The red-circle child processes indicate that if two attendees in the same chat room come in simultaneously, concurrent writings to the same log file could make data not correct. There should be a preventing mechanism called Exclusive Lock to reduce the risk.

 

Where to Store Chat Contents?

The answer is back-end. A chat log records what people chat in a web chat room. PHP scripts in servers receive new lines of message, and take responsibility of making web chat contents up-to-date.

 

Multiple Chat Rooms

Basically, each log file holds stuff of a specific web chat room. To raise meetings for more than one group, we want many web chat rooms. At this time, PHP server sites should manage each web room and its chat contents in a separated log file.

 

SECTION 2
Chat Room Layout

HTML, CSS and JS control the layout of web chat rooms. We emphasize attendee names, make content panel available to scroll, and auto anchor to the target line.

 

Chat Room Layout

At first, a prompt box always shows to ask for your chat name. Then people assign names and can chat in a default web room or create a new room. Replicated names are not inhibited, because we don’t check identity here.

Ask for Chat Name

A Default Room for JS Web Chat

 

Create a Web Chat Room

Intuitively pulling down the room list, you can join any existing chat room, and thus attend in more than one web room simultaneously. Rooms information also come from PHP server sites. If you want to create a new room, scroll to the bottom and add one.

Create a Web Chat Room

The jQuery Mobile Page Widget will help us to easily build chat room layout. The chat content block <div id="chat"></div> is empty initially, because its contents come from server sites each time.

index.php
<div data-role="page" style="background:#CCCCFF;">
    <div data-role="content">
        <div class="main-content">
            <p>Your Chat Room : <span id="room" class="namelite">  </span></p>
            <select id="room-list" class="align-left"></select>
            <p>Your Name: <span id="name" class="namelite"></span></p>
            <div id="chat"></div>
            <br>
            <input type="text" data-clear-btn="true" id="msg">
        </div>
    </div>
</div>

 

Chat Room Scrolling

In particular, the CSS portion overflow:auto contributes to the appearance of scroll bar. The chat lines in JS web room will be scrollable. Moreover, in jQuery Mobile, changing CSS attributes should be done by !important, for example, color: maroon!important.

chat.css
 .main-content { margin:0% 5%; font-size: 1em; text-shadow: none; }
 .namelite { background: #45B39D; color:white; border-radius: 5px; padding: 2px 6px; }
 .align-left { text-align: left; }
 #chat { padding:0 10px; height:350px; overflow:auto; background:white; border-radius: 5px; }
 #msg { color: maroon!important; }

 

SECTION 3
JS Web Chat

For the design of many web chat rooms, JS codes in client sites download room list, assign a default room, and allow people to create new rooms.

 

Choose a Room First

When coming in, the system assigns the default chat room to you. Still, you can select a preferred web room to chat with.

When the function get_room() gets a room list from server sites, JS codes update the selection list. Note that if not calling .selectmenu("refresh", true), the list bar will not be refreshed.

index.php
function get_room(create = false) {
    post_data = { action: "room" };
    if(create) {
        new_room = $("#name").text();
        new_room = new_room.replaceAll(' ', '-');
        new_room += "-" + Math.floor(Math.random() * Math.floor(10000));
        post_data["new"] = new_room;
    }
    console.log(post_data);
    $.ajax({
        url: "ajax-server.php",
        type: "POST",
        data: post_data,
        success: function(r) {
            console.log(r);
            obj = JSON.parse(r);
            list_rooms = "";
            for(id in obj) {
                list_rooms += "<option value='" + obj[id] + "'>CHAT ROOM : " + obj[id] + "</option>";
            }
            list_rooms += "<option value='create room'>======== CREATE A NEW ROOM ========</option>";
            $("#room-list").html(list_rooms).selectmenu("refresh", true);
            room = $("#room").text();
            if(room.trim() == "") {
                $("#room").text("default-chat");
            }
            if(create) {
                alert("CREATE A NEW ROOM : " + new_room);
                $("#room").text($("#room-list").find(":selected").val());
            }
        },
    });
}

If you want to create a new web room, set the parameter of get_room() to be true. The auto generated room name is the combination of people name and a random number.

index.html
$('#room-list').on("change", function() {
    changed = $(this).find(":selected").val();
    if(changed == "create room") {
        get_room(true);
    } else {
        $("#room").text(changed);
    }
});

Add New Room Name to The Top

 

Send Chat Messages

The function send() specifies a chat room name to push a message, and pulls whole chat contents down.

You don’t need to click a button. By handling the event keyup, people’s press on <Enter> would push messages up.

index.php
$('#msg').on("keyup", function(e) {
    if (e.keyCode == 13) send();
});

In function send(), the codes $("#chat").html(r) display up-to-date chat contents for people.

However, the contents don’t auto scroll to the bottom. So attendees can’t find what words they just entered. Auto scrolling contents down could be done by the following. That is a tricky, but useful method.

.scrollTop($('#chat')[0].scrollHeight)

index.php
function send() {
    msg = $("#msg").val();
    if(msg.trim() == "") { $("#msg").val(""); return; }
    post_data = { action: "send",
        room : $("#room").text(),
        name: $("#name").text(),
        msg: msg };
    console.log(post_data);
    $.ajax({
        url: "ajax-server.php",
        type: "POST",
        data: post_data,
        success: function(r) {
            $("#chat").html(r).scrollTop($('#chat')[0].scrollHeight);
            $("#msg").val("");
        },
    });
}

 

Polling Per Second

The function poll() requests chat data of server sites for a specific room. The action performs once per second, so if the attendee does not send messages, he can still auto receive up-to-date chat contents. The code setTimeout(poll, 1000) sets repeated interval to be 1000 milliseconds or 1 second.

index.php
function poll() {
    room = $("#room").text();
    if(room.trim() != "") {
        $.ajax({
            url: "ajax-server.php",
            type: "POST",
            data: { action: "poll", room: room },
            success: function(r) {
                $("#chat").html(r);
            },
        });
    }
    setTimeout(poll, 1000);
}

 

SECTION 4
Back-End Jobs

Finally, PHP web chat scripts in server sites formulate the chat logs to be HTML codes, prevent data files from mutual exclusion, and control web chat in many rooms.

 

Handling Send Action

If new words come to servers, PHP scripts write 3 kinds of data into chat logs. There are time, chat name, and new messages. The format of chat logs is HTML, and we highlight only the chat name by a CSS class class='namelite'. Once updated, reply to browser clients with new HTML contents.

The scenario is that Michael create a room to invite Lisa and Steve for a meeting. After discussion, Lisa thinks of other issues, and then create another room to invite Steve.

First chat room is Michael-884.

Michael-884.log
<p>07:14 <span class='namelite'>Michael</span> I join the discussion.</p>
<p>07:15 <span class='namelite'>Lisa</span> Hello, Michael. Where is Steve?</p>
<p>07:15 <span class='namelite'>Steve</span> I am here.</p>
<p>07:17 <span class='namelite'>Michael</span> Let's go camping this week. How about?</p>
<p>07:22 <span class='namelite'>Steve</span> It sounds good. But I don't have camping tents. The tents are perhaps very expensive.</p>
<p>07:24 <span class='namelite'>Lisa</span> Don't worry about it. I can borrow two tents from my brother.</p>
<p>07:32 <span class='namelite'>Steve</span> Michael, do you have camping stove?</p>
<p>07:33 <span class='namelite'>Michael</span> Sure, I have one. That is enough for us.</p>

For room Lisa-843, its chat contents and corresponding chat log file are shown below. Using F12 Inspect to see, Lisa sends chat messages with specified room and name.

JS Web Chat Room Associated with Chat Log

Lisa-843.log
<p>19:47 <span class='namelite'>Lisa</span> Hi Steve</p>
<p>19:48 <span class='namelite'>Steve</span> Hello, Lisa</p>
<p>19:50 <span class='namelite'>Lisa</span> I want to have dinner with you and Linda now.</p>
<p>19:52 <span class='namelite'>Steve</span> Which restaurant do you have idea about?</p>

Don’t forget that the race conditions may occur, suppose that many people gather in a web chat room. The option LOCK_EX makes sure the exclusive locking between concurrent writings to a single file.

ajax-server.php
switch($_POST["action"]) {
    case "send":
        $chatfile = "$chat_dir/" . $_POST["room"] . ".log";
        writeChat($chatfile);
        echo chatLog($chatfile);
        break;
    case "poll":
        $chatfile = "$chat_dir/" . $_POST["room"] . ".log";
        echo chatLog($chatfile);
        break;
    case "room":
        echo getRoom($chat_dir);
        break;
}
function writeChat($f) {
    $format = "<p>%s <span class='namelite'>%s</span> %s</p>";
    $str = sprintf($format, date("H:i"), $_POST["name"], $_POST["msg"]);
    file_put_contents($f, "$str\n", FILE_APPEND | LOCK_EX);
}

 

New Room Always on The Top

The PHP script array_merge() in getRoom() add new room on the top of room list.

ajax-server.php
function chatLog($f) {
    if(file_exists($f)) $log = file_get_contents($f); else $log = "";
    return $log;
}
function getRoom($dir) {
    $ffs = preg_grep('/^([^.])/', scandir($dir));
    $ffs = array_values($ffs);
    foreach($ffs as $key=>$ff) {
        $ffs[$key] = explode(".", $ff)[0];
    }
    //$new = $_POST['new'];
    if(isset($_POST['new'])) {
        $new = $_POST['new'];
        file_put_contents("$dir/$new" . ".log", "");
        $ffs = array_merge([ $new ], $ffs);
    }
    return json_encode($ffs);
}

Using F12 Inspect, the picture illustrates that room Lisa-843 is on the first place. Therefore, users will feel friendly when seeing the created room at first glance.

A Newly Created Web Chat Room on The Top

 

Handling Poll Action

Polling is like what our previous post about single chat room mentioned, except that the name of a web chat room should be specified.

 

FINAL
Conclusion

We have raised two brief examples for web chat rooms in PHP and JS. If you want to start learning from beginning, get the article for single chat room. Many web chat rooms are required to divide topics into several meetings.

Alternatively, using the feature of pushing messages from WebSocket servers to a specific client, you can also build chat rooms in different structure.

Thank you for reading, and we have suggested more helpful articles here. If you want to share anything, please feel free to comment below. Good luck and happy coding!

 

Learning Tips

Let us suggest a excellent way to learn HTML scripts here. Using Google Chrome F12 Inspect or Inspect Element will help you study the codes.

In Google Chrome, there are two ways to inspect a web page using the browser built-in Chrome DevTools:

  • Right-click an element on the page or in a blank area, then select Inspect.
  • Go to the Chrome menu, then select More Tools > Developer Tools.

 

Suggested Reading

 

TRY IT
Quick Experience

That is all for this project, and here is the link that let you experience the program. Please kindly leave your comments for our enhancement.

 

Try It Yourself

Click here to execute the source code, thus before studying the downloaded codes, you can check whether it is worthy.

8 thoughts on “How to Create Many Web Chat Rooms Using PHP, JS”

  1. I’m very new to web programming and PHP. How would I go about it if I don’t want to allow the user to create chat rooms but instead have a preset list of chatrooms that they can join?

    Reply
    • Preset list do simply the relationship between users and chatrooms. Just create empty files such as chat1.log, chat2.log, chat3.log in the directory ‘chat’, users can select each of those rooms from pull-down menu. You can try it.

      Reply

Leave a Comment