As I continue to improve my coding skills, I’ve really been wanting to focus on coding in PHP itself with less MySQL. To that end, I wanted to attempt a flat-file based shoutbox script written almost completely in PHP. Pictured below is the result:
What the script can do:
– It keeps the chatbox refreshed every 5 seconds (but only the chatbox itself to prevent adverse server perfomance impacts.) This makes a realtime chat feasible.
– It keeps the name you enter persistent between messages so that you don’t have to re-enter your name each time you go to send a message. (Utilizes sessions)
– It validates the name and message users enter to ensure that what was submitted isn’t empty.
– It limits the number of messages shown in the chatbox to 15 messages so that you don’t have a long page of messages and the focus is kept on the most recent messages.
Of note for admins:
– It checks to see if you have a chat log text file. If you don’t, it creates one for you and refreshes the page. This is handy if you want to test it out, delete the log file and start anew.
– It incorporates a simple CSS file which makes it easily customizable.
Script Files
The script includes 3 files: the css file that governs how the chat and message boxes look, chatbox.php which accomodates a function in the script that refreshes only the chatbox div and limits the chat messages to 15, and then the main file that features most of the code, index.php.
Without Further Ado
I’m including the code below broken down into html and php chunks along with descriptions of what’s happening in each chunk. While I was writing the script, I commented it as I went (always good practice to neatly comment your code as you go.) If you read through the code itself, it explains much more in-depth what’s happening each step of the way.
index.php
This first chunk of code checks to see if you have a chat log text file yet (shoutlog.txt). If you don’t, it will create one for you and refresh the page. It also checks to make sure that the file is writable. If it isn’t, it alerts you to change the permissions. Otherwise, it continues on. This part of the script runs after the user has submitted their name and message. It validates the user’s entries, making sure they’re not empty. If they’re empty, the script alerts the user to fill in whichever data was blank. With validated entries, the script combines the user’s name and message into a formatted sentence which is appended to the end of the shoutlog.txt file.
<?php // Simple PHP flat-file based shoutbox system // Coded by Kim Enders on 1/10/18 // the backend // where the log file is found or generated & new comments are appended $file = 'shoutlog.txt'; if (file_exists($file)) { // it exists, next check to see if it is writable if(is_writable($file)) { // let the script do its magic // get the input from the submitted form if(isset($_POST['update']) && ($_POST['update'])== "Submit Message"){ extract($_POST); // make sure that the user actually entered something for each input if($username != '' && $usermessage != '') { // some variables to format the appearance of the chat text $said = ": "; $lb = "<br />"; $uo = "<u>"; $uc = "</u>"; // concatenate the appearance & message variables into $message $message = $uo . $username . $uc . $said . $usermessage . $lb; // write the user's message to the chat log $shoutfile = fopen("shoutlog.txt", "a") or die("Unable to open file!"); fwrite($shoutfile, "\n". $message); fclose($shoutfile); } else { // find out which variable is empty and inform the user if($username == '' && $usermessage == '') { echo "The name and message can not be blank. Please try again!"; } elseif($username == '' && $usermessage != '') { echo "You cannot leave your name blank. Please try again!"; } elseif($username != '' && $usermessage == '') { echo "You cannot leave your message blank. Please try again!"; } } } } else { // warn the user to make the file writable echo "The file is not writable. Please change its permissions!"; } } else { // make a file that we can use, then re-run this page $createfile = fopen("shoutlog.txt", "a"); // find out what the main file's name is & assign it to a variable $main = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; //now refresh the page header("Location: $main"); exit; } // the front end ?>
This next chunk is the beginning of the front end of the script. It’s mostly HTML with a couple of javascripts thrown.
The first javascript snippet is based on a snippet from Mrbool.com. It causes the script to refresh the chatbox every 5 seconds. You can change that, of course on this line: }, 5000); // refreshing after every 5000 milliseconds (5 seconds)
If you want it to be every 10 seconds, you would replace 5000 with 10000. Or for every 30 seconds, you would replace 5000 with 30000. I chose to refresh in this manner since refreshing the entire page of code every 5 seconds might cause performance issues with your server. Instead, a much smaller chunk of code is refreshed and achieves the effect we want: it refreshes only the data that’s been updated and messages between users have very little delay in between so if users want to sit and chat in real time, they can.
The second javascript snippet is based on a snippet found on Stackoverflow and written by user4617883. It has a very simple but useful effect: it causes the name that you enter into the Name box to persist in between submitting messages. This way, you don’t have to keep entering your name each time you submit a message. The name is temporarily stored in sessions.
The remaining code in this chunk starts the chatbox’s outer layer (which contains only a greeting to users.)
<!DOCTYPE html> <html> <head> <title>Simple Shoutbox</title> <!-- link to the style .css file --> <link rel="stylesheet" type="text/css" href="chatbox.css"> <!-- awesome little snippet from Mr. Bool at http://mrbool.com/how-to-refresh-div-content-using-jquery/33213 --> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script> <script type="text/javascript"> var auto_refresh = setInterval( function() { $('#chatbox').load('chatbox.php').fadeIn("slow"); }, 5000); // refreshing after every 5000 milliseconds (5 seconds) </script> <!-- js snippet from user4617883 at https://stackoverflow.com/questions/36689929/how-to-retain-textbox-value-after-click-submit-button --> <!-- This snippet will cause the name you use to chat to persist with sessions --> <script type="text/javascript"> $(document).ready(function () { $("#form1").submit(function () { window.localStorage['username_val'] = $("input[name = 'username']").val(); }); $(window).load(function () { $("input[name = 'username']").val(window.localStorage['username_val']); window.localStorage['username_val'] = ''; }); }); </script> </head> <body> <div id="chatboxwrapper"> <h3>Welcome to our chat!</h3>
The next chunk of code uses the log file’s size to check and see if any messages are logged yet. A brand new log file will always be 0 kb and it starts out with no messages. So, if it’s found to be 0 kb, a message is given to the user to perhaps start a conversation. If, however, the file size is more than 0 kb, it calls the chatbox.php file (which, in turn, returns the last 15 messages of the chat.)
<?php // check to see if there are any messages yet // a fresh chat log with no messages will be 0 kb // check to see if there are any messages yet if (filesize('shoutlog.txt') == 0){ echo "There are no messages yet. Time to get the conversation started?"; } else { include("chatbox.php"); } ?>
This last chunk of the index.php file puts some space between the chatbox and the message box. It then displays the message box form. After that, the html is wrapped up with closing body and html tags.
</div> <!-- put some space between the chat box and the user message form --> <br /><br /> <!-- the user message form --> <div id="msgbox"> Join the chat by leaving a message below!<br /><br /> <form name="update_form" id="form1" method="post" action=""> Your name: <input type="text" name="username"> <br /><br /> Your message:<br /> <textarea name="usermessage" rows="4" cols="55" style="overflow: hidden"></textarea><br /> <input type="submit" name="update" id="update" class="btn" value="Submit Message"/> </form> </div> </body> </html>
chatbox.php
The entire purpose of this file is to show the last 15 lines of the chat. This keeps the script from having a very, very long page with an essentially unlimited chat to constraining the chat shown to the 15 most recent messages. This file also accommodates the aforementioned javascript snippet that relies on this file to refresh the chatbox content.
This chunk is the standard opening stuff… php tags, script identity, yada yada…
<?php // Simple PHP flat-file based shoutbox system // Coded by Kim Enders on 1/10/18 ?>
This chunk is the chatbox div and table that houses the chatbox itself.
<div id="chatbox"> <table> <tr><td>
This php snippet is based on a snippet found on Stackoverflow and written by user Byron Whitlock that limits the chat messages shown to 15. If you wanted to change the number of lines shown, you could simply change the 15 to whatever number you desire.
<?php // a useful snippet from Byron Whitlock at https://stackoverflow.com/questions/3570947/php-grab-last-15-lines-in-txt-file // It limits the lines showing in the chat to the last 15 lines $fArray = file("shoutlog.txt"); $len = sizeof($fArray); for($i=$len -15;$i<$len ;$i++) { echo $fArray[$i]; } ?>
This last chunk closes the table and div opened earlier in this file.
<!-- close the table --> </td></tr></table> </div>
chatbox.css
In case you wanted to use the basic css styling I used for the script, you can find the css below:
#chatboxwrapper { margin: 0 auto; width: 485px; border: 3px solid #C0C0C0; padding: 10px; } h1,h2,h3,h4 { margin-top: 0; text-align: center; } #msgbox { margin: 0 auto; width: 485px; border: 3px solid #C0C0C0; padding: 10px; }
Update: Due to concerns raised by my beta tester, I added a .htaccess file to the script to protect the chat log file. This keeps unwanted visitors from directly viewing or downloading the chat log. It only affects the chat log file and nothing else. The code for that file, .htaccess, follows:
#Simple PHP flat-file based shoutbox system #.htaccess file #this blocks visitors from trying to directly access or view your chat log <Files shoutlog.txt> order allow,deny deny from all </Files>
And that’s it! It’s certainly not as advanced as other scripts that employ databases, jquery, ajax and other awesome things. However, it is exactly as it was meant to be– a very basic, simple script that enables users to chat back and forth. It can easily be embedded in an existing site and further development done to it to add bells and whistles like a login system and user avatars. But that is a job for another day. I hope you found this useful!
Sungguh menakjubkan! Aku kaprah cuma orang-orang tertentu saja yang memiliki kesanggupan untuk menulis artikel sebagus ini. Mohon balas email aku untuk mengobrol tentang tulisan yang baik dan luar biasa lainnya untuk dibaca. Juga kunjungi situs aku netral88
Terima kasih telah berbagi bacaan yang cukup untuk mengisi waktu senggang. Kunjungi juga situs aku pada
Sungguh salah satu tulisan terbaik yang saya dapatkan di online. Kalau kamu memiliki niat untuk membikin bl0g bersama, dapat hubungi aku via laman yang aku buat di netral88
I don’t even know how I stopped up right here, however I thought this publish was great. I don’t recognise who you might be but certainly you are going to a famous blogger in case you are not already. Cheers!
This is certainly a great blog post. Thanks for sharing it!
This is actually a excellent post. Many thanks for sharing it!