Arkanis Development

Styles

A simple chat in about 50 lines of code

Published

Ever wanted to add a small chat to your own website? If you look around you'll find plenty of ways to do so, some use Flash, others PHP and a database and there are even some Java applets out there (they still exist!). However when searching for a really simple chat I could integrate into the website of the 6th gamesday I found nothing that satisfied me: I didn't need logins or a user management nor multiple chat rooms, just a basic chat thats simple to handle and don't need maintenance.

Because of this I created my own chat with a few lines of PHP and JavaScript. The Simple Chat project is the refined and further simplified version of this chat:

That's pretty much it. 20 lines of PHP and about 40 lines of JavaScrip (with help from jQuery I admit). Not even a database and therefore nothing to keep an eye on. Just three simple files (if you include jQuery) and you can copy them around as you like. Take a look at the source code, it's really not much. If you need a small chat for your website feel free to use this code and extend or modify it as needed.

Performance wise I was a bit surprised. I wrote a small (and lousy) Ruby script to simulate multiple clients but even with 150 simulated clients the load on the webserver and I/O was still negligible (the test script eat almost all CPU time). The test script can't simulate more than 150 clients due to threading overhead (at least that's what I suspect) and one could write another more scalable test script but with 150 clients the chat can withstand much much more than it will ever get.

I've written an in depth explanation of the architecture and code but that's something for tomorrow. For now the idea and the code should speak for them selfs. If you have questions feel free to write a comment. :)

17 comments for this post

leave a new one

#1 by
Anonymus

Would you not be better off avoiding files, instead using a separate, long-lived process that you communicate with via a socket?

#2 by
Stephan

That would avoid some I/O and the disc access. I played with the thought of using the "alternative PHP Cache" (http://www.php.net/manual/en/book.apc.php) but it's an extension and therefore you have to install it. It would also make the polling requests a bit more complicated and costly (since PHP would be involved), disable the HTTP caching and may add maintenance overhead. Something like Redis (a key-value store, http://code.google.com/p/redis/) can also be used but it would bring the same problems (but features atomic list operations).

The core aspect of all that however is to avoid the I/O associated with files and another (maybe simpler) way to achieve that would be to simply use a RAM disk for the message buffer.

However the main aspect of that chat was the simplicity and the performance is just a "positive side effect". There are other ways to build a high performance chat (e.g. a small server which uses epoll() and a lock free list) but that would be a bit more complicated. The performance to code ratio is quite well as it is now. :)

#3 by
mickeljuice

Great chat script, thank you. I've tried many chat scripts and yours does what i want. I wonder why you only have 2 comments, I thought there would be hundreds.

#4 by
P1trson

HEllo,

I've tried to test your chat, but unfortunately, when I try to send something nothing happens. I'm just trying with your example.php with following permissions:

-rwxr-xr-x. 1 root root 6459 Sep 8 2010 example.php -rwxr-xr-x. 1 root root 72174 Sep 4 2010 jquery-1.4.2.min.js -rw-rw-rw-. 1 root root 0 Apr 22 23:37 messages.json

IS there something more I need to configure ?

#5 by
Abie

The Chat works fine. I wonder if there is a way to increase the number of posts before they vanish

#6 by
Stephan

Hi Abie,

In the PHP code there is a variable named $messages_buffer_size (default 10). This is the number of messages that are kept in the JSON file. If you increase it to e.g. 50 new visitors to the chat will see the most recent 50 messages.

This page contains the entire source code of the chat (below the chat box): http://arkanis.de/projects/simple-chat/example.php It's easy to spot $messages_buffer_size there.

Note that the chat discards old messages by design. Thanks to this you can just leave the chat script on a server and it won't overflow with random garbage messages from bots.

If you want to preserve the chat messages you can enable logging. It's one commented out file_put_contents() call that is marked with "Optional". Again, see the source code. But the log is not shown in the chat itself, it's just a text file on the webserver.

In case you want to know the details of how the chat works you can read this post: http://arkanis.de/weblog/2010-09-05-simple-chat-the-details It covers the the whys and hows of the chat.

Happy programming Stephan

#7 by
Franz

Hi Stephan,

first of all thanks for your job and sharing it. I have two questions about simple chat: 1) long messages couldn't be sent, you have to split them. Is there a length limit? 2) is it possible to put a message like "write your name" if $_POST['name'] was not changed? Thanks is advance Franz

#8 by
Stephan

Hi Franz,

sorry for the late reply. I had some quite busy days setting up my own business as a freelance programmer.

About 1): The chat itself doesn't care about the message length. I did a quick test with messages up to 256 KByte and had no trouble. But the environment where you run the chat might impose limits, e.g. in the webserver configuration. Also maybe some overzealous security system inspected the message content and filtered something it wasn't supposed to filter. I haven't encountered these things but from reading the docs it's possible. If you want you can send me a mail with some details about the messages you were trying to send. Then we might be able to debug it further.

About 2): The chat is very simple and by default it can't do that. But adding it doesn't require big changes. The easiest way I can thing of is by changing line 157 of the example (http://arkanis.de/projects/simple-chat/example.php):

<input type="text" name="name" id="name" value="Anonymous" />

to

<input type="text" name="name" id="name" value="" required />

With that change the default name is empty (value="") but the user is required to enter something before sending a message (required). The browser itself will show a corresponding error message in the users language.

Hope that helps Stephan

#9 by
MyOptionalName

First, thank you for making this.

Second, people may run into the same problem I did getting php to work. After setting up the php for apache, I discovered this piece of code in mods-enabled/php*.conf:

# Running PHP scripts in user directories is disabled by default
# 
# To re-enable PHP in user directories comment the following lines
# (from <IfModule ...> to </IfModule>.) Do NOT set it to On as it
# prevents .htaccess files from disabling it.
<IfModule mod_userdir.c>
    <Directory /home/*/public_html>
        php_admin_flag engine Off
    </Directory>
</IfModule>

I AM running in my userdir directory, and this threw me for a loop. So if anybody else runs into the problem where you just get the PHP code instead of actually executing it, that may be why - you have to disable that block if you are running in your user directory (i.e. your access is something like http://127.0.0.1/~USER/script.php)

#10 by
Stephan

Oh, thanks for the heads up. Didn't know the default settings had this restriction.

#11 by
PeeterCZ

Dobrý den. Pocházím z České Republiky. Programovat neumím ale chystám vlastní web ve webnode. Zkopíroval jsem tam do odstavce html celý zdrojový kod. A nefunguje mi to.

#12 by
Genesis

Hi Stephen,

Great day! You did great! I copied your folder with the 3 files and put it in my server online then opened the example.php on Google Chrome. I typed in it and sent it. But my other browser could not see the sent chat from the 1st browser. What is wrong with what I did? Please help me.

#13 by
Tim17049

Ich habe ein kleines Problem ich kann mit Simpel Chat nicht anfangen weil die Nachrichten bei niemanden an könnten sie mir bitte Helfen?

#14 by
Michael

Good job but I'm hardware fellow and a html cut and paste thief I had for many years "a very simple ajax chat" running fine on my web site until I changed hosts. after many tries gave up and am now attempting to get this working first I use chat.kyak106.com that ends up in a box in my main web kyak106.com/lounge ..always done it this way so I could change chat without messing with the lounge. In chat.kyak106.com I uploaded (example.php) , (jquery1.4.2.min.js) and (setup.sh) just those 3 files or do I need messages.json also? Please help

#15 by
Michael

Watching this blog for help but if you are ok to write me I am Michael@kyak106.com

#16 by
Andrea

Just put Simple Chat up on my website so I can chat with my friend in the Netherlands. I was in the process of changing the layout a little and ran across something called the log file… chating.txt. It is commented out and says it is optional. I was wonder what that is and what one would use it for. Thanks.

#17 by
Stephan

The log file is just a text file where each message is appended as a new line at the end. There is no upper limit here so the log file will grow as long as you let it. Useful if you want to review longer discussions since without the log file the chat will only remember the last 10 messages.

Leave a new comment

Having thoughts on your mind about this stuff here? Want to tell me and the rest of the world your opinion? Write and post it right here. Be sure to check out the format help (focus the large text field) and give the preview button a try.

optional

Format help

Please us the following stuff to spice up your comment.

An empty line starts a new paragraph. ---- print "---- lines start/end code" ---- * List items start with a * or -

Just to keep your skill sharp and my comments clean.

or