Real-time chat application using PHP, AJAX, and file storage. This version includes the functionality of enter key to send a message and center the chat box. The chat messages are saved in a messages.txt file, and every second the chat is updated.
1. Complete Code:
Below is the updated index.php file with the enter key functionality and the chat box centered:
<?php // index.php ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Real-time Chat</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function() { // Listen for the Enter key press $('#message').keypress(function(event) { if (event.which == 13) { // 13 is the keycode for Enter event.preventDefault(); // Prevent the default line break $('#send').click(); // Trigger the click event of the send button } }); // Send message when the send button is clicked $('#send').click(function() { var message = $('#message').val(); if (message != '') { $.ajax({ url: 'send_message.php', // PHP file to handle the sending request type: 'POST', data: { message: message }, success: function(data) { $('#message').val(''); // Clear the input field loadMessages(); // Load new messages } }); } }); // Function to load messages function loadMessages() { $.ajax({ url: 'load_messages.php', // PHP file to load messages type: 'GET', success: function(data) { $('#chatbox').html(data); // Update the chatbox with new messages } }); } // Reload messages every second setInterval(loadMessages, 1000); }); </script> </head> <body> <!-- Center the chat box using a table layout --> <table width="100%" height="100%" style="border: none;"> <tr> <td align="center" valign="middle"> <div id="chat-box" style="width: 600px; background-color: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);"> <div id="chatbox" style="height: 300px; overflow-y: scroll; margin-bottom: 10px;"></div> <!-- Display chat messages --> <textarea id="message" placeholder="Type a message..." style="width: 100%; padding: 10px; font-size: 14px; border: 1px solid #ddd; border-radius: 5px; box-sizing: border-box; margin-bottom: 10px;"></textarea> <button id="send" style="width: 100%; padding: 12px; background-color: #28a745; color: white; border: none; border-radius: 5px; font-size: 16px; cursor: pointer;">Send</button> </div> </td> </tr> </table> </body> </html>
2. PHP Files to Handle the Messages:
send_message.php – Handles sending the message:
<?php // send_message.php if (isset($_POST['message'])) { $message = $_POST['message']; // Save the message to the file (messages.txt) $file = 'messages.txt'; $currentMessages = file_get_contents($file); $currentMessages .= "<p>" . htmlspecialchars($message) . "</p>"; file_put_contents($file, $currentMessages); } ?>
load_messages.php – Loads the saved messages:
<?php // load_messages.php $file = 'messages.txt'; if (file_exists($file)) { echo file_get_contents($file); // Output the content of messages.txt } ?>
3. Steps to Make it Work:
Ensure the messages are saved correctly: After sending a message, ensure that it is being saved in the messages.txt file. If the file is not created, you can manually create it:
touch messages.txt chmod 777 messages.txt # Give write permission
Verify the messages are displayed correctly: The load_messages.php file will be queried every second by AJAX, and it will return the contents of messages.txt to be displayed in the chat box.
File Permissions: Ensure that messages.txt is both readable and writable by your web server. Set the correct file permissions:
chmod 777 messages.txt
4. Explanation of Features:
Enter key functionality: When the user presses the Enter key in the message input field (#message), it triggers the click event for the Send button, effectively sending the message without needing to click the button manually.
AJAX to load messages: Every second, an AJAX call to load_messages.php is made, which reads the content of the messages.txt file and updates the #chatbox with the new messages.
Centered Chat Box: The entire chat box is centered using a table layout with align=”center” and valign=”middle”. The chat box itself is styled with some padding, a border radius, and a shadow to give it a neat look.
5. Directory and File Structure:
index.php: The main file with the chat interface and functionality.
send_message.php: Handles saving the sent messages.
load_messages.php: Loads and displays the messages from the file.
messages.txt: A text file where chat messages are stored.
6. Final Testing:
After uploading these files to your web server, open the index.php page.
Type a message in the text area and press Enter or click the Send button.
The message should be stored in the messages.txt file and immediately appear in the chat box.
If the chat box isn’t updating, check the browser console for JavaScript errors, and ensure that load_messages.php is returning the correct data.
This implementation provides a simple and functional real-time chat app without using WebSocket or any database, relying instead on file storage for chat history.