How To: PHP Chat Rooms
Full source code: repl chat-room-demo attached
- Hit "New Repl", choose "PHP Web Server" as your language, and then type "My Chat" (or something more creative) as the repl name.
- The repl will open with a simple Hello World example.
Using the PHP
fwrite uses two parameters:
- fwrite($fileobject, $value)
- $fileobject is generated using the fopen function: $fopen($filename, $mode)
- We use $mode as "a" so we can append to a file.
So now, for the chat
- We use contenteditable for rich text editing:
- Contenteditable innerHTML cannot be sent using POST. So, when it is submitted, the innerHTML is copied into a textarea that gets submitted.
method=postto the form element for secure form processing.
Posting the Message
- Create a file "post.php". Set "post.php" as the
actionattribute on the form element.
- Use PHP to retrieve the message contents.
- fwrite to topics.html.
Secure Your Software
- Right now, anyone can enter
<script src="evilscript.js"></script>in their name, and PHP will happily write the HTML as if it is preferred code.
- You can use the
htmlspecialcharsfunction to sanitize the input.
Now TEST it!
- Visit the web site you created.
- It's okay to see a "Repl Waking Up..." message after a few hours, because of the default sleeping behavior.
- If you can post messages, well done! Otherwise, look at the repl chat-room-demo to figure out what was wrong.