Here is the simplified version of the code, with only the text chatting functionality retained.
Final Version: index.html
This HTML file builds the chat window and handles the user input.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Chat Room</title> <style> body { font-family: Arial, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; } #chat-container { text-align: center; } #chat { height: 500px; overflow-y: scroll; border: 1px solid #ccc; padding: 10px; width: 600px; margin-bottom: 10px; } #message { width: 400px; } #name { display: none; } </style> </head> <body> <div id="chat-container"> <h1>Chat Room</h1> <div id="chat"></div> <input type="hidden" id="name" value=""> <input type="text" id="message" placeholder="Type your message here..."> <button onclick="sendMessage()">Send</button> </div> <script> let name = 'User' + Math.floor(Math.random() * 10000); document.getElementById('name').value = name; function sendMessage() { let message = document.getElementById('message').value; if (message.trim() === '') return; let xhr = new XMLHttpRequest(); xhr.open('POST', 'chat.php', true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.send('name=' + encodeURIComponent(name) + '&message=' + encodeURIComponent(message)); document.getElementById('message').value = ''; } function loadMessages() { let xhr = new XMLHttpRequest(); xhr.open('GET', 'chat.php', true); xhr.onload = function () { if (xhr.status === 200) { document.getElementById('chat').innerHTML = xhr.responseText; } }; xhr.send(); } document.getElementById('message').addEventListener('keydown', function(event) { if (event.key === 'Enter') { sendMessage(); event.preventDefault(); // Prevent the Enter key from submitting the form } }); setInterval(loadMessages, 1000); </script> </body> </html>
Final Version: chat.php
This PHP file handles the chat messages and stores them in a text file.
<?php $chatFile = '/usr/share/nginx/mydomain.com/chat3/chat.txt'; if ($_SERVER['REQUEST_METHOD'] === 'POST') { $name = htmlspecialchars($_POST['name']); $message = htmlspecialchars($_POST['message']); $time = date('H:i:s'); $entry = "<p><strong>$name</strong> [$time]: $message</p>n"; if (!file_exists($chatFile)) { file_put_contents($chatFile, $entry); } else { file_put_contents($chatFile, $entry, FILE_APPEND); } echo 'Message sent'; } else { if (file_exists($chatFile)) { echo file_get_contents($chatFile); } else { echo '<p>No messages yet.</p>'; } } ?>
Ensure Proper Permissions
Ensure that the chat.txt file exists and has the correct permissions:
touch /usr/share/nginx/mydomain.com/chat3/chat.txt chmod 666 /usr/share/nginx/mydomain.com/chat3/chat.txt
With these final simplified versions of the code, you will retain a functional text chat room.