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

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;

Step 2: Chat Member SingIn (live chat in php source code)

First we will create chat signin interface in signin.php to signin to chat system.

Chat SingIn:

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.

$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.







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.

getMemberDetails($_SESSION['memberid']); echo '
'; $currentSession = ''; foreach ($loggedMember as $member) { $currentSession = $member['current_session']; echo 'chat code in php with demo'; echo '

'.$member['membername'].'

'; echo ''; echo '
'; echo '
    '; echo '
  • Online

  • '; echo '
  • Away

  • '; echo '
  • Busy

  • '; echo '
  • Offline

  • '; echo '
'; echo '
'; echo '
'; echo 'Logout'; echo '
'; } echo '
'; ?>

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

'; $chatMembers = $chat->chatMembers($_SESSION['memberid']); foreach ($chatMembers as $member) { $status = 'offline'; if($member['online']) { $status = 'online'; } $activeMember = ''; if($member['memberid'] == $currentSession) { $activeMember = "active"; } echo '
  • '; echo '
    '; echo ''; echo 'chat code in php with demo'; echo '
    '; echo '

    '.$member['membername'].''.$chat->getUnreadMessageCount($member['memberid'], $_SESSION['memberid']).'

    '; echo '

    '; echo '
    '; echo '
    '; echo '
  • '; } echo ''; ?>

    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.

    getMemberDetails($currentSession); foreach ($memberDetails as $member) { echo 'chat code in php with demo'; echo '

    '.$member['membername'].'

    '; echo ''; } ?>
    getMemberChat($_SESSION['memberid'], $currentSession); ?>

    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.

    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.

    insertChat($_POST['to_member_id'], $_SESSION['memberid'], $_POST['chat_message']);
    }
    ?>
    

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

    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.

    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.

    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.

    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.

    $(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.

    updateTypingStatus($_POST["is_type"], $_SESSION["signin_details_id"]);
    }
    ?>
    The chat method updateTypingStatus() from Chat.php.
    
    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.

    fetchIsTypeStatus($_POST['to_member_id']);
    	$data = array(
    		"message" => $message			
    	);
    	echo json_encode($data);
    }
    ?>
    

    The chat method fetchIsTypeStatus() from Chat.php.

    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.

    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.

    Leave a Comment