Live chat code in php with demo and free download : Updated 2021

chat code in php with demo or Chat Web application is mainly used to communicate with people like members, friends, customers, colleagues etc. It is an important part of any business as most of It company have their chat system integrated into their online websites to communicate with their multiple clients to assist them regarding services and resolve some “live chat code in php with demo” issues.

Build Live Chat System with Ajax, PHP & MySQL [chat in php source code]

So if you’re looking for free online developing your own chat system then you’re here at right place. In this step by step post you will learn how to develop live chat system with jQuery Ajax, PHP and MySQL. I will cover this post in easy steps to develop live chat demo to create complete chat system.

live chat in php source code
live chat in php source code

As I will cover this post with live example to build live chat system with jquery Ajax, PHP & MySQL, so the major files for this example is bellow.

  • index.php
  • signin.php
  • chat.js
  • do_ajax_action.php
  • logout.php
  • Chat.php

live chat code in php free download

Step 1: Create Database Tables

We will create MySQL database tables that’s used to build chat system. So first we will create table members to store members signin information

CREATE TABLE `members` (
`memberid` int(11) NOT NULL,
`membername` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`avatar` varchar(255) NOT NULL,
`current_session` int(11) NOT NULL,
`online` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

we will also insert few members record using below insert query.

INSERT INTO `members` (`memberid`, `membername`, `password`, `avatar`, `current_session`, `online`) VALUES
(1, 'Rekha', '123', 'member1.jpg', 3, 0),
(2, 'Hardik', '123', 'member2.jpg', 1, 0),
(3, 'Minaxi', '123', 'member3.jpg', 1, 0),
(4, 'Zakhi', '123', 'member4.jpg', 0, 0),
(5, 'Geeta', '123', 'member5.jpg', 0, 0),
(6, 'Angel', '123', 'member6.jpg', 0, 0);

We will create chat table to store chat details.

CREATE TABLE `chat` (
`chatid` int(11) NOT NULL,
`sender_memberid` int(11) NOT NULL,
`reciever_memberid` int(11) NOT NULL,
`message` text NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`status` int(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

We will also create chat_signin_details table to store logged in chat activity.

CREATE TABLE `chat_signin_details` (
`id` int(11) NOT NULL,
`memberid` int(11) NOT NULL,
`last_activity` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`is_typing` enum('no','yes') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
[php]

<h3>Step 2: Chat Member SingIn (live chat in php source code)</h3>
First we will create chat signin interface in signin.php to signin to chat system.

[php]
<div class="row">
	<div class="col-sm-4">
		<h4>Chat SingIn:</h4>		
		<form method="post">
			<div class="form-group">
			<?php if ($signinError ) { ?>
				<div class="alert alert-warning"><?php echo $signinError; ?></div>
			<?php } ?>
			</div>
			<div class="form-group">
				<label for="membername">Member:</label>
				<input type="membername" class="form-control" name="membername" required>
			</div>
			<div class="form-group">
				<label for="pwd">Password:</label>
				<input type="password" class="form-control" name="pwd" required>
			</div>  
			<button type="submit" name="signin" class="btn btn-info">SingIn</button>
		</form>			
	</div>		
</div>

We will implement signin functionality on form submit in signin.php. We will include Chat.php module to handle member signin with method signinMembers(). We will store member signin details in SESSION variables for further use in system.

Read Also:  jQuery Routing using Single Page Application without framework

$signinError = '';
if (!empty($_POST['membername']) && !empty($_POST['pwd'])) {
	include ('Chat.php');
	$chat = new Chat();
	$member = $chat->signinMembers($_POST['membername'], $_POST['pwd']); 
	if(!empty($member)) {
		$_SESSION['membername'] = $member[0]['membername'];
		$_SESSION['memberid'] = $member[0]['memberid'];
		$lastInsertId = $chat->insertMemberSingInDetails($member[0]['memberid']);
		$_SESSION['signin_details_id'] = $lastInsertId;
		header("Location:index.php");
	} else {
		$signinError = "Invalid membername or password!";
	}
}

Step 3: Create Chat System HTML

In index.php, we will include Bootstrap, jQuery and CSS files to create chat system interface with Bootstrap.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel='stylesheet prefetch' 
href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.2/css/font-awesome.min.css'>
<link href="css/style.css" rel="stylesheet" id="bootstrap-css">
<script src="js/chat.js"></script>

After member logged in, it will redirect to index.php where we will display chat system with members list and member chat details. So now we will create chat system HTML to load chat details from MySQL database tables after successful member signin.

So first we will get details of current logged in chat member details from database table members using chat method getMemberDetails() from Chat.php.

<div id="profile">
<?php
include ('Chat.php');
$chat = new Chat();
$loggedMember = $chat->getMemberDetails($_SESSION['memberid']);
echo '<div class="wrap">';
$currentSession = '';
foreach ($loggedMember as $member) {
	$currentSession = $member['current_session'];
	echo '<img id="profile-img" src="memberpics/'.$member['avatar'].'" class="online" alt="" />';
	echo  '<p>'.$member['membername'].'</p>';
		echo '<i class="fa fa-chevron-down expand-button" aria-hidden="true"></i>';
		echo '<div id="status-options">';
		echo '<ul>';
			echo '<li id="status-online" class="active"><span 
class="status-circle"></span> <p>Online</p></li>';
			echo '<li id="status-away"><span class="status-circle"></span> <p>Away</p></li>';
			echo '<li id="status-busy"><span class="status-circle"></span> <p>Busy</p></li>';
			echo '<li id="status-offline"><span class="status-circle"></span> <p>Offline</p></li>';
		echo '</ul>';
		echo '</div>';
		echo '<div id="expanded">';			
		echo '<a href="logout.php">Logout</a>';
		echo '</div>';
}
echo '</div>';
?>
</div>

Now we will get details of all chat member from database table members using chat method chatMembers() from Chat.php and display members list.

<div id="contacts">	
<?php
echo '<ul>';
$chatMembers = $chat->chatMembers($_SESSION['memberid']);
foreach ($chatMembers as $member) {
	$status = 'offline';						
	if($member['online']) {
		$status = 'online';
	}
	$activeMember = '';
	if($member['memberid'] == $currentSession) {
		$activeMember = "active";
	}
	echo '<li id="'.$member['memberid'].'" class="contact '.$activeMember.'" data-tomemberid="'.$member['memberid'].'" data-tomembername="'.$member['membername'].'">';
	echo '<div class="wrap">';
	echo '<span id="status_'.$member['memberid'].'" class="contact-status '.$status.'"></span>';
	echo '<img src="memberpics/'.$member['avatar'].'" alt="" />';
	echo '<div class="meta">';
	echo '<p class="name">'.$member['membername'].'<span id="unread_'.$member['memberid'].'" 
class="unread">'.$chat->getUnreadMessageCount($member['memberid'], $_SESSION['memberid']).'</span></p>';
	echo '<p class="preview"><span id="isTyping_'.$member['memberid'].'" class="isTyping"></span></p>';
	echo '</div>';
	echo '</div>';
	echo '</li>'; 
}
echo '</ul>';
?>
</div>

and finally we will get details of current active chat member’s chat from database table chat using chat method getMemberChat() from Chat.php and display chat details.

<div class="contact-profile" id="memberSection">	
<?php
$memberDetails = $chat->getMemberDetails($currentSession);
foreach ($memberDetails as $member) {										
	echo '<img src="memberpics/'.$member['avatar'].'" alt="" />';
		echo '<p>'.$member['membername'].'</p>';
		echo '<div class="social-media">';
			echo '<i class="fa fa-facebook" aria-hidden="true"></i>';
			echo '<i class="fa fa-twitter" aria-hidden="true"></i>';
			 echo '<i class="fa fa-instagram" aria-hidden="true"></i>';
		echo '</div>';
}	
?>						
</div>
<div class="messages" id="conversation">		
<?php
echo $chat->getMemberChat($_SESSION['memberid'], $currentSession);						
?>
</div>

Step 4: Handle Member Chat Reply

We will handle message send functionality in chat.js when click message send button and call function sendMessage()

$(document).on("click", '.submit', function(event) { 
	var to_member_id = $(this).attr('id');
	to_member_id = to_member_id.replace(/chatButton/g, "");
	sendMessage(to_member_id);
});

We will create a JavaScript function sendMessage() in chat.js in which we will make Ajax request to do_ajax_action.php with action insert_chat to insert member chat to database and update member’s conversation with replied message.

Read Also:  PHP Object into Array JSON Convert SimpleXML

function sendMessage(to_member_id) {
	message = $(".message-input input").val();
	$('.message-input input').val('');
	if($.trim(message) == '') {
		return false;
	}
	$.ajax({
		url:"do_ajax_action.php",
		method:"POST",
		data:{to_member_id:to_member_id, chat_message:message, action:'insert_chat'},
		dataType: "json",
		success:function(response) {
			var resp = $.parseJSON(response);			
			$('#conversation').html(resp.conversation);				
			$(".messages").animate({ scrollTop: $('.messages').height() }, "fast");
		}
	});	
}

In do_ajax_action.php, we will call chat method insertChat() to insert chat details.

<?php
session_start();
include ('Chat.php');
if($_POST['action'] == 'insert_chat') {
	$chat->insertChat($_POST['to_member_id'], $_SESSION['memberid'], $_POST['chat_message']);
}
?>

The method insertChat() from Chat.pm to insert member chat.

<?php
public function insertChat($reciever_memberid, $member_id, $chat_message) {		
	$sqlInsert = "
		INSERT INTO ".$this->chatTable." 
		(reciever_memberid, sender_memberid, message, status) 
		VALUES ('".$reciever_memberid."', '".$member_id."', '".$chat_message."', '1')";
	$result = mysqli_query($this->dbConnect, $sqlInsert);
	if(!$result){
		return ('Error in query: '. mysqli_error());
	} else {
		$conversation = $this->getMemberChat($member_id, $reciever_memberid);
		$data = array(
			"conversation" => $conversation			
		);
		echo json_encode($data);	
	}
}
?>

Step 5: Update Chat Member list Info

In chat.js, we will create function updateMemberList() to update chat member list information like member online status by making Ajax request to do_ajax_action.php.

function updateMemberList() {
	$.ajax({
		url:"do_ajax_action.php",
		method:"POST",
		dataType: "json",
		data:{action:'update_member_list'},
		success:function(response){		
			var obj = response.profileHTML;
			Object.keys(obj).forEach(function(key) {
				// update member online/offline status
				if($("#"+obj[key].memberid).length) {
					if(obj[key].online == 1 && !$("#status_"+obj[key].memberid).hasClass('online')) {
						$("#status_"+obj[key].memberid).addClass('online');
					} else if(obj[key].online == 0){
						$("#status_"+obj[key].memberid).removeClass('online');
					}
				}				
			});			
		}
	});
}

In do_ajax_action.php, we will handle Ajax request action to return chat members information as JSON.

<?php
$chat = new Chat();
if($_POST['action'] == 'update_member_list') {
	$chatMembers = $chat->chatMembers($_SESSION['memberid']);
	$data = array(
		"profileHTML" => $chatMembers,	
	);
	echo json_encode($data);	
}
?>

Step 6: Update Active Member Chat Details

In chat.js, we will create function updateMemberChat() to update active member chat details by making Ajax request to do_ajax_action.php.

function updateMemberChat() {
	$('li.contact.active').each(function(){
		var to_member_id = $(this).attr('data-tomemberid');
		$.ajax({
			url:"do_ajax_action.php",
			method:"POST",
			data:{to_member_id:to_member_id, action:'update_member_chat'},
			dataType: "json",
			success:function(response){				
				$('#conversation').html(response.conversation);			
			}
		});
	});
}

In do_ajax_action.php, we will handle Ajax request action to return chat details as JSON data response.

<?php
$chat = new Chat();
if($_POST['action'] == 'update_member_chat') {
	$conversation = $chat->getMemberChat($_SESSION['memberid'], $_POST['to_member_id']);
	$data = array(
		"conversation" => $conversation			
	);
	echo json_encode($data);
}
?>

Step 7: Update Member’s Unread Message Count

In chat.js, we will create function updateUnreadMessageCount() to update member unread message count by making Ajax request to do_ajax_action.php.

function updateUnreadMessageCount() {
	$('li.contact').each(function(){
		if(!$(this).hasClass('active')) {
			var to_member_id = $(this).attr('data-tomemberid');
			$.ajax({
				url:"do_ajax_action.php",
				method:"POST",
				data:{to_member_id:to_member_id, action:'update_unread_message'},
				dataType: "json",
				success:function(response){		
					if(response.count) {
						$('#unread_'+to_member_id).html(response.count);	
					}					
				}
			});
		}
	});
}

In do_ajax_action.php, we will handle Ajax request action to return member’s unread message count as JSON data response.

<?php
$chat = new Chat();
if($_POST['action'] == 'update_unread_message') {
	$count = $chat->getUnreadMessageCount($_POST['to_member_id'], $_SESSION['memberid']);
	$data = array(
		"count" => $count			
	);
	echo json_encode($data);
}
?>

Step 8: Update Member Typing Status

In chat.js, we will handle member’s typing status by making Ajax request to do_ajax_action.php to update typing as yes if member typing on input focus event.

Read Also:  Helper classess in laravel 6 Example - PHP

$(document).on('focus', '.message-input', function(){
		var is_type = 'yes';
		$.ajax({
			url:"do_ajax_action.php",
			method:"POST",
			data:{is_type:is_type, action:'update_typing_status'},
			success:function(){
			}
		});
	}); 

We will also update typing status as no if member stop typing on input blur event

$(document).on('blur', '.message-input', function(){
	var is_type = 'no';
	$.ajax({
		url:"do_ajax_action.php",
		method:"POST",
		data:{is_type:is_type, action:'update_typing_status'},
		success:function() {
		}
	});
}); 	

In do_ajax_action.php, we will update member’s typing status to database table.

<?php
$chat = new Chat();
if($_POST['action'] == 'update_typing_status') {
	$chat->updateTypingStatus($_POST["is_type"], $_SESSION["signin_details_id"]);
}
?>
The chat method updateTypingStatus() from Chat.php.

<?php
public function updateTypingStatus($is_type, $signinDetailsId) {		
	$sqlUpdate = "
		UPDATE ".$this->chatSingInDetailsTable." 
		SET is_typing = '".$is_type."' 
		WHERE id = '".$signinDetailsId."'";
	mysqli_query($this->dbConnect, $sqlUpdate);
}	
?>	

Step 9: Get Member Typing Status

In chat.js, we will create function showTypingStatus() to show member typing status by making Ajax request to do_ajax_action.php.

function showTypingStatus() {
	$('li.contact.active').each(function(){
		var to_member_id = $(this).attr('data-tomemberid');
		$.ajax({
			url:"do_ajax_action.php",
			method:"POST",
			data:{to_member_id:to_member_id, action:'show_typing_status'},
			dataType: "json",
			success:function(response){				
				$('#isTyping_'+to_member_id).html(response.message);			
			}
		});
	});
}

In do_ajax_action.php, we will handle Ajax request action to return member’s member typing status as JSON data response.

<?php
$chat = new Chat();
if($_POST['action'] == 'show_typing_status') {
	$message = $chat->fetchIsTypeStatus($_POST['to_member_id']);
	$data = array(
		"message" => $message			
	);
	echo json_encode($data);
}
?>

The chat method fetchIsTypeStatus() from Chat.php.

<?php
public function fetchIsTypeStatus($memberId){
	$sqlQuery = "
	SELECT is_typing FROM ".$this->chatSingInDetailsTable." 
	WHERE memberid = '".$memberId."' ORDER BY last_activity DESC LIMIT 1"; 
	$result =  $this->getData($sqlQuery);
	$output = '';
	foreach($result as $row) {
		if($row["is_typing"] == 'yes'){
			$output = ' - Typing...';
		}
	}
	return $output;
}		
?>

Step 10: Handle Chat Member Logout (chat in php source code)

In logout.php, we will handle member logout functionality and update member offline status.

<?php
session_start();
include ('Chat.php');
$chat = new Chat();
$chat->updateMemberOnline($_SESSION['memberid'], 0);
$_SESSION['membername'] = "";
$_SESSION['memberid']  = "";
$_SESSION['signin_details_id']= "";
header("Location:index.php");
?>

I hope you get an idea about chat code in php with demo.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.