Continuing my exploration of what can be done as a web app made of one single PHP file (cf previous article), I decided to make an online chat app. I won't distribute the code of that one because we live in a dangerous world, and I'll just simply explain how I did it in this article. If you need code to make your own, others' are available on the web anyway (here for example).
Jumping to the conclusion first, yes it's possible to make an online chat app with one single PHP file, under 900 lines. No dependencies, no config, just copy the file on a PHP server and immediately start to use it. A user can create several rooms, invite other users to his rooms, chat in parallel in several rooms. New users can create accounts (protected by password) by sending request to an admin user, which approves them through a confirmation email automatically generated. Messages are not persistent (they are lost when the user leaves the app), but they are pooled if the user is not online. The app looks like this:
There are two versions of the DOM. The returned one depends on whether the user is logged in or not.
The login version of the DOM has two forms, one for login and account creation, and one for the chat itself. The account creation add the user to the database and send an email to the admin with a link to the login page and a confirmation key. When the admin clicks the link and logs in, the confirmation key is checked and if correct the user entry in the database is updated, enabling the user to login. The email address is not stored in the database but added to the confirmation email such as the admin can contact the user to discuss about the account creation if necessary.
The chat version of the DOM has two main divs, the 'menu' one and the 'rooms' one. The user can switch between them with buttons Close/Menu, which simply toggles the 'display' property of these divs. The 'menu' div allows to create/terminate room, add/dismiss users from the rooms, switch the current room, see the list of users in the current room. The 'rooms' div displays the messages in the current room, and allow the user to send new messages. If messages are pending in rooms other than the current one, a button on the right side alerts the user and allows to jump to these rooms.