Learn to Code via Tutorials on Repl.it!

← Back to all posts
How To: PHP Chat Rooms
weeklyd3 (0)

Full source code: repl chat-room-demo attached

Starting Steps

  • 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 function

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.

Login

  • You will see that the software uses cookies. It is stored as soon as the user logs in. If your browser has cookies disabled, it will not work!

So now, for the chat

  • We use contenteditable for rich text editing:
<div contenteditable="true" id="msg">Type your message here!</div>
  • Contenteditable innerHTML cannot be sent using POST. So, when it is submitted, the innerHTML is copied into a textarea that gets submitted.
  • Add method=post to the form element for secure form processing.

Posting the Message

  • Create a file "post.php". Set "post.php" as the action attribute 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 htmlspecialchars function 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.
Comments
hotnewtop
codingjlu (227)

Who says innerHTML can't be sent from POST?