CSS/CSS3 Javascript/JQuery PHP

How to create a Simple PHP File Based Chat Room Application

A chat application plays a very vital role in online communication today. It plays a key role in success of various platforms like Facebook, Google, WhatsApp, Skype, Hike and many others. It has also become a part of online support system these days. I know coding geeks always curious about it and wondered that how a chat application actually works. Some of those geeks has also tried to implement some sort of such application as I tried as well during my college days.

So guys here I am going to start a series of tutorials on “How to create a chat application” starting with this first tutorial. In this tutorial you will learn how to create a very basic simple php file based chat room application. Lets start with the basic flow of any chat application.

chat-flow

Let me explain you this chat flow chart. Generally a chat model has a three basic components as you can see in the above flow chart. User, Chat Controller and Model. Role of chat controller is to take the message from one user, get it stored in a model (say a DB table) and route it to the other user.

In this application, that I am going to explain below, also has three components. But we are going to use a data file as model instead of DB table. We’ll do it later tutorials. HTML, CSS3 and jQuery is used in this application for designing the UI and controls in frontend. This application has main 5 files:

  1. index.php (Front view of the application)
  2. chat.php (The controller)
  3. chatdata.txt (The Model)
  4. style.css (Stylesheet)
  5. jquery library file

Content of these files(except jquery library and chatdata.txt) are given below. Codes are well commented wherever required.

Content of index.php:

<?php
session_start();

//Create a session of username and logging in the user to the chat room
if(isset($_POST['username'])){
	$_SESSION['username']=$_POST['username'];
}

//Unset session and logging out user from the chat room
if(isset($_GET['logout'])){
	unset($_SESSION['username']);
	header('Location:index.php');
}

?>
<html>
<head>
	<title>Simple Chat Room</title>
	<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,400,300' rel='stylesheet' type='text/css'>
	<link rel="stylesheet" href="css/style.css" />
	<script type="text/javascript" src="js/jquery-1.10.2.min.js" ></script>
</head>
<body>
<div class='header'>
	<h1>
		SIMPLE CHAT ROOM
		<?php // Adding the logout link only for logged in users  ?>
		<?php if(isset($_SESSION['username'])) { ?>
			<a class='logout' href="?logout">Logout</a>
		<?php } ?>
	</h1>

</div>

<div class='main'>
<?php //Check if the user is logged in or not ?>
<?php if(isset($_SESSION['username'])) { ?>
<div id='result'></div>
<div class='chatcontrols'>
	<form method="post" onsubmit="return submitchat();">
	<input type='text' name='chat' id='chatbox' autocomplete="off" placeholder="ENTER CHAT HERE" />
	<input type='submit' name='send' id='send' class='btn btn-send' value='Send' />
	<input type='button' name='clear' class='btn btn-clear' id='clear' value='X' title="Clear Chat" />
</form>
<script>
// Javascript function to submit new chat entered by user
function submitchat(){
		if($('#chat').val()=='' || $('#chatbox').val()==' ') return false;
		$.ajax({
			url:'chat.php',
			data:{chat:$('#chatbox').val(),ajaxsend:true},
			method:'post',
			success:function(data){
				$('#result').html(data); // Get the chat records and add it to result div
				$('#chatbox').val(''); //Clear chat box after successful submition
				document.getElementById('result').scrollTop=document.getElementById('result').scrollHeight; // Bring the scrollbar to bottom of the chat resultbox in case of long chatbox
			}
		})
		return false;
};

// Function to continously check the some has submitted any new chat
setInterval(function(){
	$.ajax({
			url:'chat.php',
			data:{ajaxget:true},
			method:'post',
			success:function(data){
				$('#result').html(data);
			}
	})
},1000);

// Function to chat history
$(document).ready(function(){
	$('#clear').click(function(){
		if(!confirm('Are you sure you want to clear chat?'))
			return false;
		$.ajax({
			url:'chat.php',
			data:{username:"<?php echo $_SESSION['username'] ?>",ajaxclear:true},
			method:'post',
			success:function(data){
				$('#result').html(data);
			}
		})
	})
})
</script>
<?php } else { ?>
<div class='userscreen'>
	<form method="post">
		<input type='text' class='input-user' placeholder="ENTER YOUR NAME HERE" name='username' />
		<input type='submit' class='btn btn-user' value='START CHAT' />
	</form>
</div>
<?php } ?>

</div>
</body>
</html>

 

Content of Chat.php

<?php
session_start();

if(isset($_POST['ajaxsend']) && $_POST['ajaxsend']==true){
	// Code to save and send chat
	$chat = fopen("chatdata.txt", "a");
	$data="<b>".$_SESSION['username'].':</b> '.$_POST['chat']."<br>";
	fwrite($chat,$data);
	fclose($chat);

	$chat = fopen("chatdata.txt", "r");
	echo fread($chat,filesize("chatdata.txt"));
	fclose($chat);
} else if(isset($_POST['ajaxget']) && $_POST['ajaxget']==true){
	// Code to send chat history to the user
	$chat = fopen("chatdata.txt", "r");
	echo fread($chat,filesize("chatdata.txt"));
	fclose($chat);
} else if(isset($_POST['ajaxclear']) && $_POST['ajaxclear']==true){
	// Code to clear chat history
	$chat = fopen("chatdata.txt", "w");
	$data="<b>".$_SESSION['username'].'</b> cleared chat<br>';
	fwrite($chat,$data);
	fclose($chat);
}

 

Content of style.css

body{margin:0; padding: 0; font-family: 'Open Sans', sans-serif, arial; font-size: 14px; background: #e07070; overflow: hidden;}
*{font-family: 'Open Sans', sans-serif, arial; font-size: 14px; color:#555; }
.main{max-width:1024px; width:100%; margin:auto;}
.header{background: #3B5898}
.header h1{max-width:1024px; width:100%; margin:0 auto; padding:10px 0; font-size: 20px; color: #fff; text-align: center; font-weight: 300}
.userscreen{margin: auto; text-align: center; margin-top: 24%}
.input-user {
  padding: 10px;
  border: solid 2px #c9c9c9;
  transition: border 0.3s;
  width:250px;
}
.input-user:focus,
.input-user.focus {
  border: solid 2px #726da5;
}

.btn {
	-moz-box-shadow:inset 0px 1px 0px 0px #7a8eb9;
	-webkit-box-shadow:inset 0px 1px 0px 0px #7a8eb9;
	box-shadow:inset 0px 1px 0px 0px #7a8eb9;
	background:-webkit-gradient(linear, left top, left bottom, color-stop(0.05, #637aad), color-stop(1, #5972a7));
	background:-moz-linear-gradient(top, #637aad 5%, #5972a7 100%);
	background:-webkit-linear-gradient(top, #637aad 5%, #5972a7 100%);
	background:-o-linear-gradient(top, #637aad 5%, #5972a7 100%);
	background:-ms-linear-gradient(top, #637aad 5%, #5972a7 100%);
	background:linear-gradient(to bottom, #637aad 5%, #5972a7 100%);
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#637aad', endColorstr='#5972a7',GradientType=0);
	background-color:#637aad;
	border:1px solid #314179;
	display:inline-block;
	cursor:pointer;
	color:#ffffff;
	font-family: 'Open Sans', sans-serif, arial;
	font-size:13px;
	padding:6px 12px;
	text-decoration:none;
}
.btn:hover {
	background:-webkit-gradient(linear, left top, left bottom, color-stop(0.05, #5972a7), color-stop(1, #637aad));
	background:-moz-linear-gradient(top, #5972a7 5%, #637aad 100%);
	background:-webkit-linear-gradient(top, #5972a7 5%, #637aad 100%);
	background:-o-linear-gradient(top, #5972a7 5%, #637aad 100%);
	background:-ms-linear-gradient(top, #5972a7 5%, #637aad 100%);
	background:linear-gradient(to bottom, #5972a7 5%, #637aad 100%);
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#5972a7', endColorstr='#637aad',GradientType=0);
	background-color:#5972a7;
}
.btn:active {
	position:relative;
	top:1px;
}

.btn-user{padding:9px 30px; position: relative; top: 0px; font-size: 16px; font-weight: 300}

#result{max-width:1024px; width:100%; padding:10px; background: #f1f1f1; max-height: 80%; overflow-y:auto;}

.chatcontrols{position: fixed; bottom: 0; width: 100%}
.chatcontrols form{margin: 0}
#chatbox 
{
    background: none repeat scroll 0 0 #FCFCFC;
    border: 1px solid #777;
    border-radius: 2px 2px 2px 2px;
    color: #6C6C6C;
    height: 35px;
    margin-top: 10px;
    outline: medium none;
    padding: 10px 10px;
    width: 65.5%;
    height: 60px;
    font-size: 20px;
    font-weight: 300
}
#chatbox:focus{
    background: none repeat scroll 0 0 white;
    border-color: #555;
    box-shadow: 0 0 2px rgba(0, 0, 0, 0.3) inset;
    color: #A6A6A6;
 	content:"";
}

.btn-send{font-size: 20px; padding: 15px; font-weight: 300}
.btn-clear{padding: 15px 25px; font-size: 20px; font-weight: 300}
.logout{float: right; color: #fff; text-decoration: none; font-size: 15px}

 

DOWNLOAD CODE

About the author

Sujeet Kr Singh