This article is to describe a simple chat application in php or web chat application.
When think about how to create chat application in php we can understand that. each user accessing
the webpage get a separate instance of the webpage and there have no direct
connection between two users using the same page at the same time.So we can use
a sql database to communicate with two users.
Online chat application in php means a chat application using ajax or in othe words
a jquery chat application.
When think about how to create chat application in php we can understand that. each user accessing
the webpage get a separate instance of the webpage and there have no direct
connection between two users using the same page at the same time.So we can use
a sql database to communicate with two users.
Online chat application in php means a chat application using ajax or in othe words
a jquery chat application.
You can download the complete zip file fromthis link:-
https://dl.dropboxusercontent.com/s/rv6aejvbqgphg61/openchat_part1.zip
To know how to install and use watch this video. (Click the gear icon and select video quality to 1080p HD, then click the full screen button for good quality)
Go to this link to subscribe to my YouTube channel to stay updated:- https://www.youtube.com/channel/UCxTp2yDew9m48Ch_hArOoYw
Here is the source code for chat application in php
Here have two files index.php and back.php
code
index.php
<html>
<head>
</head>
<body>
<table width="100%" height="100%" border="1" align="center" valign="center">
<tr><td colspan="2" height="6%"><h3>Chat Window</h3></td></tr>
<tr><td colspan="2" height="6%"> From(Your Name or Id): <input type="text" name="sender" id="sender"><br></td></tr>
<tr><td width='85%'>
<div id="chat_view" >
</div>
</td>
<td>
<div id="users" name="users">Online Users</div>
</td>
</tr>
</table>
<div id="chat_list"></div>
<style type="text/css">
.chat_box{
border-style:solid;
border-width:medium;
width:200px;
height:300px;
float:left;
}
#msg{
width:200px;
height:200px;
overflow:auto;
}
#new_msg_text
{
width:200px;
height:50px;
}
#close_button{
width:20px;
height:20px;
}
.user_list{
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
window.setInterval(function() {
viewMsg();
viewOnlineUsers();
createNewChatBox();
},1000);
});
function creatNewBox(receiver)
{
var newbox ="<div class='chat_box' id='chat_box_"+receiver+"'>"+
"<div id='chat_header'><input type='text' name='receiver[]' READONLY value='"+
receiver+"' id='receiver'><img id='close_button' src='images/close_button.jpg' alt='X' onclick='closeWindow($(this))'/></div>"+
"<div height='20%' id='msg' >"+
"<br><br><br></div>"+
"<div id='newmsg'><textarea rows='4' cols='10' id='new_msg_text'> </textarea></div>"+
"<input type='button' id='btn' onclick='saveMsg($(this))'>"+
"</div>";
return newbox;
}
function createNewChatBox()
{
var sender=$("#sender").val();
$("#chat_list").load('back.php?opt=get_chat&sender='+sender);
$("input[name='chat_users[]']").each(function(){
viewBox($(this).val());
});
}
function viewBox(receiver)
{
if($.trim($("#sender").val())==$.trim(receiver))
return;
$(document).ready(function(){
var flag=false;
$("input[name='receiver[]']").each(function(){
if($(this).val()==receiver)
{flag=true;}
});
if(flag==false)$("#chat_view").append(creatNewBox(receiver));
});
}
function viewOnlineUsers()
{
var sender=$("#sender").val();
$("#users").load('back.php?opt=view_users&sender='+sender);
}
function closeWindow(obj)
{
obj.parent().parent().remove();
}
function viewMsg()
{
var sender=$("#sender").val();
$("input[name='receiver[]']").each(function(){
var receiver=$(this).val();
$("#chat_box_"+receiver).find("#msg").load('back.php?opt=view_msg&sender='+sender+"&receiver="+receiver);
});
}
function saveMsg(obj)
{
var receiver=obj.parent().find("#receiver").val();
var sender=$("#sender").val();
var msg=obj.parent().find("#new_msg_text").val();
$.ajax({
type: 'POST',
url: 'back.php?opt=save',
data: {"receiver":receiver,"sender":sender,"msg":msg},
success: function(){
alert("success");
}
});
}
</script>
</body>
</html>
<head>
</head>
<body>
<table width="100%" height="100%" border="1" align="center" valign="center">
<tr><td colspan="2" height="6%"><h3>Chat Window</h3></td></tr>
<tr><td colspan="2" height="6%"> From(Your Name or Id): <input type="text" name="sender" id="sender"><br></td></tr>
<tr><td width='85%'>
<div id="chat_view" >
</div>
</td>
<td>
<div id="users" name="users">Online Users</div>
</td>
</tr>
</table>
<div id="chat_list"></div>
<style type="text/css">
.chat_box{
border-style:solid;
border-width:medium;
width:200px;
height:300px;
float:left;
}
#msg{
width:200px;
height:200px;
overflow:auto;
}
#new_msg_text
{
width:200px;
height:50px;
}
#close_button{
width:20px;
height:20px;
}
.user_list{
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
window.setInterval(function() {
viewMsg();
viewOnlineUsers();
createNewChatBox();
},1000);
});
function creatNewBox(receiver)
{
var newbox ="<div class='chat_box' id='chat_box_"+receiver+"'>"+
"<div id='chat_header'><input type='text' name='receiver[]' READONLY value='"+
receiver+"' id='receiver'><img id='close_button' src='images/close_button.jpg' alt='X' onclick='closeWindow($(this))'/></div>"+
"<div height='20%' id='msg' >"+
"<br><br><br></div>"+
"<div id='newmsg'><textarea rows='4' cols='10' id='new_msg_text'> </textarea></div>"+
"<input type='button' id='btn' onclick='saveMsg($(this))'>"+
"</div>";
return newbox;
}
function createNewChatBox()
{
var sender=$("#sender").val();
$("#chat_list").load('back.php?opt=get_chat&sender='+sender);
$("input[name='chat_users[]']").each(function(){
viewBox($(this).val());
});
}
function viewBox(receiver)
{
if($.trim($("#sender").val())==$.trim(receiver))
return;
$(document).ready(function(){
var flag=false;
$("input[name='receiver[]']").each(function(){
if($(this).val()==receiver)
{flag=true;}
});
if(flag==false)$("#chat_view").append(creatNewBox(receiver));
});
}
function viewOnlineUsers()
{
var sender=$("#sender").val();
$("#users").load('back.php?opt=view_users&sender='+sender);
}
function closeWindow(obj)
{
obj.parent().parent().remove();
}
function viewMsg()
{
var sender=$("#sender").val();
$("input[name='receiver[]']").each(function(){
var receiver=$(this).val();
$("#chat_box_"+receiver).find("#msg").load('back.php?opt=view_msg&sender='+sender+"&receiver="+receiver);
});
}
function saveMsg(obj)
{
var receiver=obj.parent().find("#receiver").val();
var sender=$("#sender").val();
var msg=obj.parent().find("#new_msg_text").val();
$.ajax({
type: 'POST',
url: 'back.php?opt=save',
data: {"receiver":receiver,"sender":sender,"msg":msg},
success: function(){
alert("success");
}
});
}
</script>
</body>
</html>
back.php
<?php
extract($_POST);
extract($_GET);
$con = mysql_connect('localhost', 'root', '');
mysql_select_db('sukesh');
switch ($opt) {
case "save":
$query = "INSERT INTO chat (sender,receiver,msg,time) values('" . $sender . "','" . $receiver . "','" . $msg . "',NOW()" . ")";
mysql_query($query, $con) or die("Error...");
break;
case "view_msg":
$query = "SELECT * FROM chat WHERE receiver='" . $sender. "' AND sender='".$receiver."'";
$r = mysql_query($query, $con) or die("Error...");
while ($row = mysql_fetch_array($r)) {
echo "<table><tr>";
echo "<td>".$row['msg']."</td>";
echo "</tr></table>";
}
break;
case "get_chat":
$query = "SELECT DISTINCT sender from chat ".
" WHERE receiver='$sender' AND AddTime(time, '00:00:15')>=NOW()";
echo $query ;
$r = mysql_query($query, $con) or die("Error...3");
while ($row = mysql_fetch_array($r)) {
echo "<input type='text' name='chat_users[]' value='".$row['sender']."'>";
}
break;
case "view_users":
$query = "SELECT count(*) as count FROM users WHERE user_id='".$sender."'";
$r=mysql_query($query, $con) or die("Error...1");
$row = mysql_fetch_array($r);
if($row['count']>0)
$query = "UPDATE users SET last_visit=NOW() WHERE user_id='".$sender."'";
else
$query = "INSERT INTO users (user_id,last_visit) values('".$sender."',NOW())";
mysql_query($query, $con) or die("Error...2");
$query = "SELECT * FROM users WHERE AddTime(last_visit, '00:00:15')>=NOW()";
$r = mysql_query($query, $con) or die("Error...3");
while ($row = mysql_fetch_array($r)) {
echo "<table><tr>";
echo "<td><a onclick=\"viewBox('".$row['user_id']."')\">".$row['user_id']."</a></td>";
echo "</tr></table>";
}
break;
}
?>
extract($_POST);
extract($_GET);
$con = mysql_connect('localhost', 'root', '');
mysql_select_db('sukesh');
switch ($opt) {
case "save":
$query = "INSERT INTO chat (sender,receiver,msg,time) values('" . $sender . "','" . $receiver . "','" . $msg . "',NOW()" . ")";
mysql_query($query, $con) or die("Error...");
break;
case "view_msg":
$query = "SELECT * FROM chat WHERE receiver='" . $sender. "' AND sender='".$receiver."'";
$r = mysql_query($query, $con) or die("Error...");
while ($row = mysql_fetch_array($r)) {
echo "<table><tr>";
echo "<td>".$row['msg']."</td>";
echo "</tr></table>";
}
break;
case "get_chat":
$query = "SELECT DISTINCT sender from chat ".
" WHERE receiver='$sender' AND AddTime(time, '00:00:15')>=NOW()";
echo $query ;
$r = mysql_query($query, $con) or die("Error...3");
while ($row = mysql_fetch_array($r)) {
echo "<input type='text' name='chat_users[]' value='".$row['sender']."'>";
}
break;
case "view_users":
$query = "SELECT count(*) as count FROM users WHERE user_id='".$sender."'";
$r=mysql_query($query, $con) or die("Error...1");
$row = mysql_fetch_array($r);
if($row['count']>0)
$query = "UPDATE users SET last_visit=NOW() WHERE user_id='".$sender."'";
else
$query = "INSERT INTO users (user_id,last_visit) values('".$sender."',NOW())";
mysql_query($query, $con) or die("Error...2");
$query = "SELECT * FROM users WHERE AddTime(last_visit, '00:00:15')>=NOW()";
$r = mysql_query($query, $con) or die("Error...3");
while ($row = mysql_fetch_array($r)) {
echo "<table><tr>";
echo "<td><a onclick=\"viewBox('".$row['user_id']."')\">".$row['user_id']."</a></td>";
echo "</tr></table>";
}
break;
}
?>
Here I am using two Mysql tables namely chat and users
chat
users
The query to make this tables
chat
CREATE TABLE IF NOT EXISTS `chat` (
`sender` varchar(255) DEFAULT NULL,
`receiver` varchar(255) DEFAULT NULL,
`msg` text,
`time` datetime DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
users
CREATE TABLE IF NOT EXISTS `users` (
`user_id` varchar(255) NOT NULL,
`last_visit` datetime NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
You can also read :- Chat application using a database table in PHP - Part 2
ths coding is use but i need mulitple user chatting application in php like LinkedIn sir..
ReplyDeleteDid you mean a group chat?
DeleteFor what you want this chat application?If you are trying to make a social networking site,then download dolphin framework and make changes to it as your like.
If you trying to make this application to group chat,it will be easy.
not working fine its showing only display no chatting is posoble... tell me how to do it plzzz.....
ReplyDeletehi friend,
ReplyDelete1.First in the 'From(Your Name or Id):' text field enter your name
2.In the right panel with heading 'Online Users' you can see the online peoples who are available to chat. Unfortunately you can't see anyone in that list,because
there hasn't any chance for another person using this chat at
the time when you are using it because of the limited pageview of my blog.So you must open the same URL in another tab, then you can see your name
in the previous tab is listed in the online user list.
3.Type another name in this new tab
4. click your name from the online users list.You can see a small chat window is populated.In this window you can type
the message and send it by click in the send button
Thank you
hello, in this chat application not viewing the receiver command from receiver and also sender command from sender how to create this
DeleteHi Karthikeyan,
ReplyDeleteIt is a limitation of my chat application.I will fix it in the next update.
Edit back.php like this
in the case "view_msg": edit the query like this
$query = "SELECT * FROM chat WHERE (receiver='" . $sender. "' AND sender='".$receiver."') OR (receiver='".$receiver."' and sender='". $sender."') order by time ";
I am sorry about this,because it is not a tested code segment.But I believe that it will works for you.
SELECT DISTINCT sender from chat WHERE receiver='' AND AddTime(time, '00:00:15')>=NOW()Error...3
Deletehey.. thanx for the code... i need a help. what if i want to display the name of the message sender.... i know its a bit silly but i am very new to php so can u plz tell me how.
ReplyDeleteHi Kodali,
DeleteNow the current code is displaying the sender name in a text box at the top of the chat box.
ya its displaying but i want the name of the mesage writer against each msg too...
ReplyDeletelike if a and b are conversing..
a's chat box
a:hii
b:how r u??
a:i am fyn.. hw r u??
b's chatbox
a:hii
b:how r u??
a:i am fyn.. hw r u??
Thanx in advance
plz put it on view msg td $row['sender']."::".$row['msg']
Deletedude if i want to include smilet feature .. like if i enter something as :) it should display appropriate smiley image
ReplyDeleteAnonymous ,
ReplyDeleteYou are correct.Thanks for your effort.For a few a days I was busy.So I can't reply to brayan and Kodali Deepika.
I will give you a reply as soon as possible.
hai sukesh thanks for your support ..actualy i am stuck on msg sending..how can i send a mesage on presing enter key make it fazt..itz very urgent..
ReplyDeleteAnonymous,
ReplyDeleteadd this code in the function
creatNewBox(receiver) and try again.It may work
$("#new_msg_text").keypress(function (e) {
e.preventDefault();
var key = window.event ? e.keyCode : e.which;
if (key == '13') {
saveMsg($(this));
}
});
1.how can i minimize a winodow when new window open
Delete2.display invisible users(not in online)
i hope that you will finish it on tomorrow
DeleteMinimise the window will be a big task,and it requires more time to complete.I will implement it in the next update.
ReplyDeleteTheir is no login is implemented now.So we can't identify the invisible users
chat not working in IE ....
DeleteGreat Work ..This is wonderful......
ReplyDeletegteat working
ReplyDeletegud application
ReplyDeleteit is useful
i have one doubt
i want to know the working procedure of this application by using andriod emulators
hi Venkatesh,
ReplyDeletetry phonegap.
http://docs.phonegap.com/
thanks sukesh
Deletecan u please provide supported java files for these application to deploy in a emulator
This comment has been removed by the author.
ReplyDeletenice application thanx
ReplyDeletehow to provide secure login in it and then start chatting?
How can i modify it admin-clients chat(one -many )?help me soon
ReplyDeletewithout creating form in html is it possible
ReplyDeleteand how about xml response in AJAX
ReplyDeleteOnline Group Chat Script with full Source code & demo
ReplyDeletehttp://grprajapat.blogspot.in/2014/09/chat-script-in-php-with-full-source.html
hai sukesh Chat application using a database table in PHP will not work different browser
ReplyDeletewil you send the script and guide of work in different browser such as chrome,internetexplorer
hai sukesh Chat application using a database table in PHP will not work different browser
ReplyDeletewil you send the script and guide of work in different browser such as chrome,internetexplorer
excellent application... working perfectly.. gppd luck brother..
ReplyDeleteI Would like to Share about GroupRocket.Net, I do work for GroupRocket, You May think, My Comment is bias but I do believe GroupRocket is helpful for communication at work or making chatting about work even better.
ReplyDeleteExcellent work..I would like to ad this chat box in my blog. Please guide me, how to ad this to a blogger post. All the steps required. Thank you
ReplyDeletewhat is the complexity of you chat
ReplyDeletewhat is the complexity of you chat
ReplyDeleteI like the valuable information on chat application you provide in your articles. I’ll bookmark your weblog and check again here often. Best of luck for the next! Thanks for such post and keep it up.
ReplyDeletewhat is dolhpin framework
ReplyDeleteArticles can examine the relationship between music and memory, exploring its therapeutic potential for individuals with memory-related conditions. Nord VPN Offer Articles can investigate the impact of climate change on vulnerable populations.
ReplyDelete