PHP Code

How to Build a Simple Chat Application with PHP

Do you have an online support system with which you'd like to be able to enable live chat? Well, you can either pay for a service hosted by a 3rd party, or you could easily just build one yourself unsing PHP. This simple chat system will take user input from an HTML form, store it in a text file, and display it on the screen.

Save the code below as chat.php. Also, you'll need to create a writeable text file called msg.txt, in the same directory.

There is code included to

  • strip HTML markup
  • set the max number of chat messages displayed. the default is 10
  • set a maximum filesize for msg.txt (default is about 100Kb). When it hits the maximum, it archives the old messages to a past message text file.
  • 
    <?
    $person = str_replace ("\n"," ", $person);
    $person = str_replace ("<", " ", $person); //take out HTML tags
    $person = str_replace (">", " ", $person); 
    $person = stripslashes ($person);
    ?>
    <form action="chat.php" method="post">
    Nickname: <input type="text" name="person" size="40" maxlength="80" value="<? echo $person; ?>"><br>
    Your message: <textarea name="message" rows="3" cols="40"></textarea>
    <input type="submit" value="Send/refresh">
    </form>
    <?
    
    $chat_file_ok = "./msg.txt";
    $chat_length = 10;
    
    $max_single_msg_length = 100000;
    $max_file_size = $chat_length * $max_single_msg_length;
    
    $file_size= filesize($chat_file);
    
    			
    if ($file_size > $max_file_size) {
    
    // reads file and stores each line $lines' array elements
    $lines = file($chat_file_ok);
    //get number of lines
    
    $a = count($lines);
    
    $u = $a - $chat_lenght;
    for($i = $a; $i >= $u ;$i--){
    		$msg_old =  $lines[$i] . $msg_old;
    	}
    $deleted = unlink($chat_file_ok);
    $fp = fopen($chat_file_ok, "a+");
    $fw = fwrite($fp, $msg_old);
    fclose($fp);
    }
    
    // every message has to be placed into one single line in the msg.txt file.  You can render \n (new lines) with "<br>" html tag
    
    $msg = str_replace ("\n"," ", $message);
    
    //	if the user writes something the new message is appended to the msg.txt file
    		
    // strip avoid buggy html code and slashes
    $msg = str_replace ("\n"," ", $message);
    $msg = str_replace ("<", " ", $msg);
    $msg = str_replace (">", " ", $msg);
    $msg = stripslashes ($msg);
    
    if ($msg != ""){
    
    $fp = fopen($chat_file_ok, "a+");
    $fw = fwrite($fp, "\n<b>$person :</b> $msg<br>");
    fclose($fp);
    }
    
    $lines = file($chat_file_ok);
    $a = count($lines);
    
    $u = $a - $chat_lenght;
    
    /*	reads the array in reverse order and outputs to chat	*/
    for($i = $a; $i >= $u ;$i--){
    		echo $lines[$i] . "<hr>";
    	}
    
    ?>
    
    Share

13 Comments

  1. hey can i do a complete chat application with the above code??????
    im very much new to php…….
    can u help

  2. You might want to check out PHPmychat for that

  3. I want concept of implementing chat,wuold u help me

    It's a nice code

  4. Hi this Niki and i have got this Script can you tell me that what is all it need to be a simple Chat script on it and can you give me some idea only how it is working can you do that HELP for me

  5. I Think It Would Be Much Faster If It Used Sqlite3 Or MySQL, Instead Of An ASCII Text File. Also How Can I Take This Simple Script, And Turn It Into A Realtime Chat System, I Guess What I Mean Is, How Do You Load Something And Save Something, after the page has loaded with php?I Don't Think You Can, So You Will Either Need Flash, Or JavaScript, Or Java(Don't Use Java, It Is Super-Duper-Uber Gay!), Or CGI, Or Python(Probably The Easiest!).

  6. the above code doesn't work, while not finished (archiving old msg file) the below script fixes the remaining functionality & bugs.
    <?php
    error_reporting(E_ALL ^ E_NOTICE);
    if (isset($_POST['person'])){
    $person=$_POST['person'];
    $person = str_replace ("\n"," ", $person);
    $person = str_replace ("", " ", $person);
    $person = stripslashes ($person);
    }

    ?>

    Nickname: <input type="text" name="person" size="40" maxlength="80" value="">
    Your message:

    $max_file_size) {

    // reads file and stores each line $lines' array elements
    $lines = file($chat_file_ok);
    //get number of lines

    $a = count($lines);

    $u = $a – $chat_length;
    for($i = $a; $i >= $u ;$i–){
    $msg_old = $lines[$i] . $msg_old;
    }
    $deleted = unlink($chat_file_ok);
    $fp = fopen($chat_file_ok, "a+");
    $fw = fwrite($fp, $msg_old);
    fclose($fp);
    }

    if (!isset($_POST["Send/refresh"])){
    // every message has to be placed into one single line in the msg.txt file. You can render \n (new lines) with "" html tag
    $message = $_POST['message'];
    $msg = str_replace ("\n"," ", $message);

    // if the user writes something the new message is appended to the msg.txt file

    // strip avoid buggy html code and slashes
    $msg = str_replace ("\n"," ", $message);
    $msg = str_replace ("", " ", $msg);
    $msg = stripslashes ($msg);

    if ($msg != ""){

    $fp = fopen($chat_file_ok, "a+");
    $fw = fwrite($fp, "\n$person : $msg");
    fclose($fp);
    }
    }
    $lines = file($chat_file_ok);
    $a = count($lines);

    $u = ($a – $chat_length)+$chat_length;

    /* reads the array in reverse order and outputs to chat */
    for($i = $u; $i >= 0 ;$i–){
    echo $lines[$i] . "";
    }

    ?>

  7. im new in php but that code is not working and i dont know how to fix it. anyone can write normal code?

  8. any way all that i can say is thank you for the chat code although i have not yet tested it
    all that i want you to help you people to help me with is a code for a discussion forum and a calendar thank you.

  9. So, maybe I'm an idiot, but I don't actually see any php here. just the html?

  10. Please i will love if oyu could modify the code and remove the small errors of syntaxe i will be very greatful for thet thanks

  11. Hi, I need an entire chat application for around 50 users in my company. i dnt want to give them any sort of special rights so they can access the Internet, just one application ready to add users and for them to start chatting.

  12. Hey man, nyc work!!!!
    Em loooking to take php chat application as a project for my next semester as em lookin to create a flash front end ….
    can u help me on tht??????

  13. A nice chat example.

Leave a Reply

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image