Exercise : Chat-It (by Katlyn Edwards)

chatpic

Given this basic skeleton page, add in the necessary form components and PHP to make a minimalistic chat page. You can see a completed version here.

The form needs a place for the user to type in their name, a place for the user to type their message, and a submit button.

The PHP part has two phases. If the page has post data to the form, it should save the data to chat.txt in the following format: name:message\n Remember to set the correct permissions on chat.txt so that the server can write to it.

The other part of the PHP should display the text file into the div with an id of "chatlog". The names should be bold then followed by " says: " and the message. Each message should be it's own paragraph.

Exercise Solution

  <body>
    <?php  
    if(isset($_POST["name"]) && isset($_POST["message"])) {
      file_put_contents("chat.txt", $_POST["name"] . ":" . $_POST["message"] . "\n", FILE_APPEND);
    } ?>
    <div id="chatlog">
       <?php
          $messages = file("chat.txt", FILE_IGNORE_NEW_LINES);
          foreach($messages as $message) {
             $parts = explode(":", $message); ?>
             <p><strong><?= $parts[0] ?></strong> says: &quot;<?= $parts[1] ?>&quot;</p>
          <?php } ?>
    </div>
    <form action="chat.php" method="post">
       Name: <input type="text" name="name" /><br/>
       Message: <input type="text" name="message" /><br/>
       <input type="submit" value="Send!" /> 
    </form>
  </body>