[trick] Membuat Chat Ala Facebook dengan php mysql

database

chat.php


<?php
define ('DBPATH','localhost');
define ('DBUSER','root');
define ('DBPASS','12345');
define ('DBNAME','dbchat');

session_start();

global $dbh;
$dbh = mysql_connect(DBPATH,DBUSER,DBPASS);
mysql_selectdb(DBNAME,$dbh);

if ($_GET['action'] == "chatheartbeat") { chatHeartbeat(); }
if ($_GET['action'] == "sendchat") { sendChat(); }
if ($_GET['action'] == "closechat") { closeChat(); }
if ($_GET['action'] == "startchatsession") { startChatSession(); }

if (!isset($_SESSION['chatHistory'])) {
$_SESSION['chatHistory'] = array();
}

if (!isset($_SESSION['openChatBoxes'])) {
$_SESSION['openChatBoxes'] = array();
}

function chatHeartbeat() {

$sql = "SELECT * FROM chat where (chatto = '".mysql_real_escape_string($_SESSION['username'])."' AND recd = 0) ORDER BY id ASC";
$query = mysql_query($sql);
$items = '';

$chatBoxes = array();

while ($chat = mysql_fetch_array($query)) {

if (!isset($_SESSION['openChatBoxes'][$chat['from']]) && isset($_SESSION['chatHistory'][$chat['from']])) {
$items = $_SESSION['chatHistory'][$chat['from']];
}

$chat['message'] = sanitize($chat['message']);

$items .= <<<EOD
{
"s": "0",
"f": "{$chat['from']}",
"m": "{$chat['message']}"
},
EOD;

if (!isset($_SESSION['chatHistory'][$chat['from']])) {
$_SESSION['chatHistory'][$chat['from']] = '';
}

$_SESSION['chatHistory'][$chat['from']] .= <<<EOD
{
"s": "0",
"f": "{$chat['from']}",
"m": "{$chat['message']}"
},
EOD;

unset($_SESSION['tsChatBoxes'][$chat['from']]);
$_SESSION['openChatBoxes'][$chat['from']] = $chat['sent'];
}

if (!empty($_SESSION['openChatBoxes'])) {
foreach ($_SESSION['openChatBoxes'] as $chatbox => $time) {
if (!isset($_SESSION['tsChatBoxes'][$chatbox])) {
$now = time()-strtotime($time);
$time = date('g:iA M dS', strtotime($time));

$message = "Sent at $time";
if ($now > 180) {
$items .= <<<EOD
{
"s": "2",
"f": "$chatbox",
"m": "{$message}"
},
EOD;

if (!isset($_SESSION['chatHistory'][$chatbox])) {
$_SESSION['chatHistory'][$chatbox] = '';
}

$_SESSION['chatHistory'][$chatbox] .= <<<EOD
{
"s": "2",
"f": "$chatbox",
"m": "{$message}"
},
EOD;
$_SESSION['tsChatBoxes'][$chatbox] = 1;
}
}
}
}

$sql = "UPDATE chat set RECD = 1 where chatto = '".mysql_real_escape_string($_SESSION['username'])."' AND recd = 0";
$query = mysql_query($sql);

if ($items != '') {
$items = substr($items, 0, -1);
}
header('Content-type: application/json');
?>
{
"items": [
<?php echo $items;?>
]
}

<?php
exit(0);
}

function chatBoxSession($chatbox) {

$items = '';

if (isset($_SESSION['chatHistory'][$chatbox])) {
$items = $_SESSION['chatHistory'][$chatbox];
}

return $items;
}

function startChatSession() {
$items = '';
if (!empty($_SESSION['openChatBoxes'])) {
foreach ($_SESSION['openChatBoxes'] as $chatbox => $void) {
$items .= chatBoxSession($chatbox);
}
}
if ($items != '') {
$items = substr($items, 0, -1);
}

header('Content-type: application/json');
?>
{
"username": "<?php echo $_SESSION['username'];?>",
"items": [
<?php echo $items;?>
]
}

<?php
exit(0);
}

function sendChat() {
$from = $_SESSION['username'];
$to = $_POST['to'];
$message = $_POST['message'];

$_SESSION['openChatBoxes'][$_POST['to']] = date('Y-m-d H:i:s', time());

$messagesan = sanitize($message);

if (!isset($_SESSION['chatHistory'][$_POST['to']])) {
$_SESSION['chatHistory'][$_POST['to']] = '';
}

$_SESSION['chatHistory'][$_POST['to']] .= <<<EOD
{
"s": "1",
"f": "{$to}",
"m": "{$messagesan}"
},
EOD;
unset($_SESSION['tsChatBoxes'][$_POST['to']]);

$sql = "INSERT INTO chat (chatfrom,chatto,message,sent) values ('".mysql_real_escape_string($from)."', '".mysql_real_escape_string($to)."','".mysql_real_escape_string($message)."',NOW())";
$query = mysql_query($sql);
echo "1";
exit(0);
}

function closeChat() {

unset($_SESSION['openChatBoxes'][$_POST['chatbox']]);

echo "1";
exit(0);
}

function sanitize($text) {
$text = htmlspecialchars($text, ENT_QUOTES);
$text = str_replace("\n\r","\n",$text);
$text = str_replace("\r\n","\n",$text);
$text = str_replace("\n","<br>",$text);
return $text;
}
?>

chat.js


<?php
session_start();
$_SESSION['username'] = "takehikoboyz" // Must be already set
?>

<html>
<head>
<title>Live Chat</title>

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/chat.js"></script>

<style>
body {
background-color: #eeeeee;
padding:0;
margin:0 auto;
font-family:"Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
font-size:11px;
}
</style>

<link type="text/css" rel="stylesheet" media="all" href="css/chat.css" />
<link type="text/css" rel="stylesheet" media="all" href="css/screen.css" />

</head>
<body>
<div id="main_container">

<a href="javascript:void(0)" onClick="javascript:chatWith('desta')">Chat With Desta</a>
<a href="javascript:void(0)" onClick="javascript:chatWith('chendy')">Chat With Chendy</a>

</div>

</body>
</html>

tampilan

 

 

download code disini

Leave a comment

4 Comments

  1. keren da..

    Reply
  2. Mantabbb… open source juga (y)

    Reply
  3. manftap gan, tapi lawan chatnya gimana ??

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: