PHP chat code in php with demo – chat in PHP with example script

Today, We want to share with you chat code in php with demo.In this post we will show you chat application in php using ajax, hear for chat system in php we will give you demo and example for implement.In this post, we will learn about How to integrate whatsapp Api php for send and receive message in bulk with an example.

Build Live Chat System with Ajax, PHP & MySQL

This sort of utility would be complete for a live chat support system for your online website Application in chat code in php with demo.

Online Chat System or Chat application is mainly used to communicate with users, people like friends, employees, customers, colleagues etc.

Create Database Tables

Example 1:

CREATE TABLE `converse_employees` (
`employeeid` int(11) NOT NULL,
`employeename` 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;

INSERT INTO `converse_employees` (`employeeid`, `employeename`, `password`, `avatar`, `current_session`, `online`) VALUES
(1, 'Janaki', '123', 'employee1.jpg', 3, 0),
(2, 'Sejal', '123', 'employee2.jpg', 1, 0),
(3, 'Kinjal', '123', 'employee3.jpg', 1, 0),
(4, 'Meera', '123', 'employee4.jpg', 0, 0),
(5, 'Bhavika', '123', 'employee5.jpg', 0, 0),
(6, 'Dhara', '123', 'employee6.jpg', 0, 0);

CREATE TABLE `converse` (
`converseid` int(11) NOT NULL,
`sender_employeeid` int(11) NOT NULL,
`reciever_employeeid` 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;

CREATE TABLE `converse_login_details` (
`id` int(11) NOT NULL,
`employeeid` int(11) NOT NULL,
`last_activity` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`is_typing` enum('no','yes') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Login Page

<div class="row">
	<div class="col-sm-4">
		<h4>Communicate Login:</h4>		
		<form method="post">
			<div class="form-group">
			<?php if ($loginError ) { ?>
				<div class="alert alert-warning"><?php echo $loginError; ?></div>
			<?php } ?>
			</div>
			<div class="form-group">
				<label for="employeename">Employee:</label>
				<input type="employeename" class="form-control" name="employeename" 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="login" class="btn btn-info">Login</button>
		</form>			
	</div>		
</div>

login.php

$loginError = '';
if (!empty($_POST['employeename']) && !empty($_POST['pwd'])) {
	include ('Communicate.php');
	$converse = new Communicate();
	$employee = $converse->loginEmployees($_POST['employeename'], $_POST['pwd']); 
	if(!empty($employee)) {
		$_SESSION['employeename'] = $employee[0]['employeename'];
		$_SESSION['employeeid'] = $employee[0]['employeeid'];
		$lastInsertId = $converse->insertEmployeeLoginDetails($employee[0]['employeeid']);
		$_SESSION['login_details_id'] = $lastInsertId;
		header("Location:index.php");
	} else {
		$loginError = "Invalid employeename or password!";
	}
}

index.php

<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/converse.js"></script>

Communicate.php

<div id="profile">
<?php
include ('Communicate.php');
$converse = new Communicate();
$loggedEmployee = $converse->getEmployeeDetails($_SESSION['employeeid']);
echo '<div class="wrap">';
$currentSession = '';
foreach ($loggedEmployee as $employee) {
	$currentSession = $employee['current_session'];
	echo '<img id="profile-img" src="employeepics/'.$employee['avatar'].'" class="online" alt="" />';
	echo  '<p>'.$employee['employeename'].'</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>

<div id="contacts">	
<?php
echo '<ul>';
$converseEmployees = $converse->converseEmployees($_SESSION['employeeid']);
foreach ($converseEmployees as $employee) {
	$status = 'offline';						
	if($employee['online']) {
		$status = 'online';
	}
	$activeEmployee = '';
	if($employee['employeeid'] == $currentSession) {
		$activeEmployee = "active";
	}
	echo '<li id="'.$employee['employeeid'].'" class="contact '.$activeEmployee.'" data-toemployeeid="'.$employee['employeeid'].'" data-toemployeename="'.$employee['employeename'].'">';
	echo '<div class="wrap">';
	echo '<span id="status_'.$employee['employeeid'].'" class="contact-status '.$status.'"></span>';
	echo '<img src="employeepics/'.$employee['avatar'].'" alt="" />';
	echo '<div class="meta">';
	echo '<p class="name">'.$employee['employeename'].'<span id="unread_'.$employee['employeeid'].'" class="unread">'.$converse->getUnreadMessageCount($employee['employeeid'], $_SESSION['employeeid']).'</span></p>';
	echo '<p class="preview"><span id="isTyping_'.$employee['employeeid'].'" class="isTyping"></span></p>';
	echo '</div>';
	echo '</div>';
	echo '</li>'; 
}
echo '</ul>';
?>
</div>

Communicate.php

<div class="contact-profile" id="employeeSection">	
<?php
$employeeDetails = $converse->getEmployeeDetails($currentSession);
foreach ($employeeDetails as $employee) {										
	echo '<img src="employeepics/'.$employee['avatar'].'" alt="" />';
		echo '<p>'.$employee['employeename'].'</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 $converse->getEmployeeCommunicate($_SESSION['employeeid'], $currentSession);						
?>
</div>

converse.js

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

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

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

function updateEmployeeCommunicate() {
	$('li.contact.active').each(function(){
		var to_employee_id = $(this).attr('data-toemployeeid');
		$.ajax({
			url:"converse_action.php",
			method:"POST",
			data:{to_employee_id:to_employee_id, action:'update_employee_converse'},
			dataType: "json",
			success:function(response){				
				$('#conversation').html(response.conversation);			
			}
		});
	});
}

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

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

converse_action.php

<?php
session_start();
include ('Communicate.php');

$converse = new Communicate();
if($_POST['action'] == 'show_typing_status') {
	$message = $converse->fetchIsTypeStatus($_POST['to_employee_id']);
	$data = array(
		"message" => $message			
	);
	echo json_encode($data);
}

if($_POST['action'] == 'insert_converse') {
	$converse->insertCommunicate($_POST['to_employee_id'], $_SESSION['employeeid'], $_POST['converse_message']);
}


if($_POST['action'] == 'update_typing_status') {
	$converse->updateTypingStatus($_POST["is_type"], $_SESSION["login_details_id"]);
}

if($_POST['action'] == 'update_unread_message') {
	$count = $converse->getUnreadMessageCount($_POST['to_employee_id'], $_SESSION['employeeid']);
	$data = array(
		"count" => $count			
	);
	echo json_encode($data);
}

if($_POST['action'] == 'update_employee_converse') {
	$conversation = $converse->getEmployeeCommunicate($_SESSION['employeeid'], $_POST['to_employee_id']);
	$data = array(
		"conversation" => $conversation			
	);
	echo json_encode($data);
}

if($_POST['action'] == 'update_employee_list') {
	$converseEmployees = $converse->converseEmployees($_SESSION['employeeid']);
	$data = array(
		"profileHTML" => $converseEmployees,	
	);
	echo json_encode($data);	
}

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

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

Communicate.php

<?php
public function fetchIsTypeStatus($employeeId){
	$sqlQuery = "
	SELECT is_typing FROM ".$this->converseLoginDetailsTable." 
	WHERE employeeid = '".$employeeId."' 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;
}

public function updateTypingStatus($is_type, $loginDetailsId) {		
	$sqlUpdate = "
		UPDATE ".$this->converseLoginDetailsTable." 
		SET is_typing = '".$is_type."' 
		WHERE id = '".$loginDetailsId."'";
	mysqli_query($this->dbConnect, $sqlUpdate);
}	

public function insertCommunicate($reciever_employeeid, $employee_id, $converse_message) {		
	$sqlInsert = "
		INSERT INTO ".$this->converseTable." 
		(reciever_employeeid, sender_employeeid, message, status) 
		VALUES ('".$reciever_employeeid."', '".$employee_id."', '".$converse_message."', '1')";
	$result = mysqli_query($this->dbConnect, $sqlInsert);
	if(!$result){
		return ('Error in query: '. mysqli_error());
	} else {
		$conversation = $this->getEmployeeCommunicate($employee_id, $reciever_employeeid);
		$data = array(
			"conversation" => $conversation			
		);
		echo json_encode($data);	
	}
}
?>

logout.php

<?php
session_start();
include ('Communicate.php');
$converse = new Communicate();
$converse->updateEmployeeOnline($_SESSION['employeeid'], 0);
$_SESSION['employeename'] = "";
$_SESSION['employeeid']  = "";
$_SESSION['login_details_id']= "";
header("Location:index.php");
?>

I hope you get an idea about chat system in php.
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.