Chat2: Group Chat Room with PHP, jQuery, and a Text File

Avatar of Chris Coyier
Chris Coyier on (Updated on )

📣 Freelancers, Developers, and Part-Time Agency Owners: Kickstart Your Own Digital Agency with UACADEMY Launch by UGURUS 📣

This is an update to original Chat Room we published here on CSS-Tricks. In some ways, the technology is the same. We are going to employ PHP to talk to the server, jQuery to keep the chat rolling, and the chats themselves will be stored in .txt files just like the first version.

What is changed is the addition of some new features:

  • Usernames are unique to users currently chatting
  • You can see a “currently chatting” user list
  • There are multiple rooms for chatting

A Little MySQL

While the first version of this used no database at all, we are going to employ a little MySQL for this version. There is a file in the download called Setup.sql for use in building the initial database. MySQL isn’t for the chats themselves, but for two other things:

  • Keeping track of active users
  • The rooms

When someone comes in to chat, they choose a username. Using some jQuery, it makes an AJAX request to see if that username is currently in use in the database. If it is in use, you get a warning:

Otherwise, it says it’s cool:

If it is cool, and you click to join the chats, that username will be put into the database and thus further checks for it’s name will tell others that name is unavailable. Idle users are removed from the database.

Adding/Editing/Removing Rooms

The names of the chatrooms are kept in the database. To add a new chatroom, just add a new row to the database with the name of the chatroom and the filename of the text file you intend to store the chat:

Then it’s just a matter of making sure the text file is on the server in the right place with proper server-writeable file permissions (see the download for properly location).

jQuery

I’m sure you’ve noticed by now we haven’t been looking at any actual code. This is on purpose. All the code is available in the download (see below). It is not so incredibly much that it’s overwhelming, but I think it’s too much for a standard written tutorial/overview. Instead, let’s overview what it’s responsible for:

Username checking: On the homepage of the chat, when you choose your username, jQuery is there watching that text input. When you type a character (on keyup) it asks a certain PHP file (via AJAX) if that username is in use. The PHP file responds with a yes or no, and a message is appended to the screen accordingly.

Message box: When a user types into the textarea for sending a message, the jQuery watches that box and ensures the text is under a certain number of characters (set via maxlength attribute on the textarea)

Sending message: When the return/enter key is pressed in the chat box the value of it is sent for processing. PHP writes the text to the text file.

Updating the chat: Every few seconds, jQuery asks a PHP file to poll the text file to see if there are any new lines, if there are, they are displayed.

Features it doesn’t have

  • You can’t kick people out
  • It doesn’t do special characters

You wanna add that stuff in? I’d love it and I’ll update this.

Demo and Download

Download Files

UPDATE: It turns out there was a SECURITY PROBLEM with one particular aspect of it, which can get grant access to any file on the server. A reader was able to show me how they could publicly access my wp-config.php WordPress file, which is of course super sensitive. The vulnerability is in the update.php file, which accepts a “state” and “file” parameter. Accessed directly, and with a relative file path, you can get access to protected files that way. When it gets fixed I’ll update the downloadable code.

UPDATE: Jason Gradwell suggested some protection on the PHP side, which would require the filed to be called via Ajax only and only from a specific source.

<?php if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_REFERER']!="http://your-site.com/path/to/chat.js") { 
  die(); 
} ?>

Credits

Special thanks to Kenrick Beckett who created the original code that powered this and Jason Lengstorf for looking it over and tidying some things up security-wise.

For the Future

Here is a roundup of things people have suggested in the comments or that I otherwise think would be cool:

  • Security problem from above fixed
  • Flood control (something like you can only submit 1 message every 5 seconds)
  • Link to logout (delete PHP session)
  • Allow some HTML, but not other (whitelist of tags). Like allow <a href=””>, but still strip out javascript. Possibly a few buttons for HTML (WYSIWYG?). Code highlighting for stuff in <code> tags.
  • Allow registration, for being able to have a certain username permanently (and all the stuff that goes with that, like “lost password”)
  • Protection against non-existent chat room names e.g. /Chat2/room/?name=LOL
  • Support for all special characters (UTF-8)
  • Private messages (@) (only the person who matches that username will see it)
  • Kick people out / ban people by IP (only as an admin user, or perhaps just a blacklist of IPs)
  • More emoticons
  • Have an actual submit button (for mobile devices that support JavaScript but don’t have regular key events)
  • Automatic filtering of bad words
  • Utilize an outside login system, like Twitter oAuth, Google Login, or Facebook Connect
  • Usernames as emails, then use Gravatars
  • Links with 4-letter extensions don’t work (e.g. .info)
  • Long polling, instead of requesting every few seconds