- How to Create Many Web Chat Rooms Using PHP, JS
- EXPLORE THIS ARTICLE TABLE OF CONTENTS
- BONUS Source Code Download
- Download Guideline
- SECTION 1 Multiple Chat Rooms
- Client-Server View
- Where to Store Chat Contents?
- Multiple Chat Rooms
- SECTION 2 Chat Room Layout
- Chat Room Layout
- Create a Web Chat Room
- Chat Room Scrolling
- SECTION 3 JS Web Chat
- Choose a Room First
- Send Chat Messages
- Polling Per Second
- SECTION 4 Back-End Jobs
- Handling Send Action
- New Room Always on The Top
- Handling Poll Action
- FINAL Conclusion
- Learning Tips
- Suggested Reading
- TRY IT Quick Experience
- Try It Yourself
- PHP объектно-ориентированное гостиничное приложение
- 4 ответа
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
EXPLORE THIS ARTICLE
TABLE OF CONTENTS
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.
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.
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.
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.
The jQuery Mobile Page Widget will help us to easily build chat room layout. The chat content block is empty initially, because its contents come from server sites each time.
Your Chat Room : Your Name: 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 .
.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
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.
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 += ""; > list_rooms += ""; $("#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.
$('#room-list').on("change", function() < changed = $(this).find(":selected").val(); if(changed == "create room") < get_room(true); >else < $("#room").text(changed); >>);

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 would push messages up.
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.
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.
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.
07:14 Michael I join the discussion.
07:15 Lisa Hello, Michael. Where is Steve?
07:15 Steve I am here.
07:17 Michael Let's go camping this week. How about?
07:22 Steve It sounds good. But I don't have camping tents. The tents are perhaps very expensive.
07:24 Lisa Don't worry about it. I can borrow two tents from my brother.
07:32 Steve Michael, do you have camping stove?
07:33 Michael Sure, I have one. That is enough for us.
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.

19:47 Lisa Hi Steve
19:48 Steve Hello, Lisa
19:50 Lisa I want to have dinner with you and Linda now.
19:52 Steve Which restaurant do you have idea about?
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.
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 = "%s %s %s
"; $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.
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.

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.
PHP объектно-ориентированное гостиничное приложение
В данный момент я программирую объектно-ориентированное гостиничное приложение для изучения ООП. Я выбрал это, потому что в моей книге (PHP Design Patterns от O’Reilly) они программировали компанию по прокату автомобилей. Теперь я закончил с основной бизнес-логикой, но у меня все еще есть некоторые проблемы.
В отеле класса есть следующие методы:
//All public functions, left it hhere cause of the length checkOut( HotelRoom $room, DateTime $from, DateTime $to ) changeRoom( HotelRoom $oldRoom, HotelRoom $newRoom, HotelCustomer $customer, DateTime $from, DateTime $to) checkOut( HotelRoom $room, DateTime $from, DateTime $to )
Поэтому для каждого шага, который я делаю (бронирование, изменение номера или оформление заказа), я должен передать HotelRoom в качестве параметра. В каждой комнате есть идентификатор и номер. Будет ли лучше реализовать метод addRoom(HotelRoom $room) и хранить все комнаты в охраняемой собственности $rooms массив, а затем только передать HotelRoom::$id для методов или есть лучший способ?
Я относительно новичок в ООП и просто хочу узнать, что является хорошей практикой.
4 ответа
Я не сделал бы ваш Hotel класс, ответственный за ваши три функции, которые вы упомянули. Это очень специфические функции, тогда как Hotel это очень широкий класс.
Рассмотреть возможность RoomManager и CustomerManager учебный класс. Введите эти классы в Hotel класс, и пусть они несут ответственность за получение Room и Customer «S. Room а также Customer класс должен содержать определенные функции, которые вы наметили:
class Hotel < public $roomManager; public $customerManager; public function __construct(RoomManager $rm, CustomerManager $cm) < $this->roomManager = $rm; $this->customerManager = $cm; > // . > class RoomManager < public function getRoom($id) < // find room where Room->id == $id; return $room; > // some other stuff may become relevant in here > class CustomerManager < public function getCustomer($id) < // find customer where Customer->id == $id; return $customer; > // some other stuff may become relevant in here > class Room < public function checkout(DateTime $from, DateTime $to) < // . >> class Customer < private $room; public function setRoom(Room $hr) < $this->room = $hr; > >
Код клиента будет что-то вроде:
// instantiate a Hotel and inject its 2 dependencies $hotel = new Hotel(new RoomManager, new CustomerManager); // checkout Room 3 $hotel->roomManager->getRoom(3)->checkout(); // change Customer 2's Room from Room 3 to Room 4 $newRoom = $hotel->roomManager->getRoom(4); $hotel->customerManager->getCustomer(2)->setRoom($newRoom);
Обратите внимание, как ответственность ваших классов стала более конкретной. Hotel класс просто хочет управлять конкретными компонентами.