gmail – facebook like chat with codeigniter

Well here is the new tutorial about famous "Gmail and Facebook like chat".

This tutorial will not have any demo link for now.

As we all know the original work was done by Anant Garg. He has made it a paid script now. Though when it was new i had a chance to grab the free version (you can find it in the attached zip file)

lets start

First you need a database table to set up, a simple chat table that would save the chat log.

CREATE TABLE `chat` (   `id` int(10) unsigned NOT NULL 
AUTO_INCREMENT,   `from` varchar(255) NOT NULL DEFAULT '',   `to` 
varchar(255) NOT NULL DEFAULT '',   `message` text NOT NULL,   `sent` 
datetime NOT NULL DEFAULT '0000-00-00 00:00:00',   `recd` int(10) 
unsigned NOT NULL DEFAULT '0',   PRIMARY KEY (`id`) )

next what u need to do is simply download my code file. Extract the archive and save thing to your root folder.

Once your files are in place and you have your database and its table created, open codeigniter's database file located (as on my setup) "ciChat/application/config/database.php"

and change your database credentials.

// as per my setup   
$db['default']['hostname'] = 'localhost';   
$db['default']['username'] = 'root';   
$db['default']['password'] = 'whatever';   
$db['default']['database'] = 'test';

save and close the file.

Open a file located at (as on my setup) "ciChat/chat/chat.php". Update the databse credentials here.

define ('DBPATH','localhost');   
define ('DBUSER','root');   
define ('DBPASS','whatever');   
define ('DBNAME','test');

save and close.

Now since database is all set up, lets get started in codeigniter. When i got this code i tried hard for making codeigniter classes and lot more stuff, but after loads of discussion on CI forum, i found it was pretty simple.

To start a chat interface simply load a view in the index function of "ciChat/application/controllers/welcome.php"

public function index()     {         $this->load->view('startChat');     }

My start chat code gives you links and options to have one to one chat between two persons and on different browsers.

startChat.php view


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"    "http://www.w3.org/TR/html4/strict.dtd"    >
<html lang="en">
<head>
    <title>Gmail/Facebook Like Chat</title>
    <style type="text/css">
        .wrapper
        {
            width: 390px;
            margin: 100px auto;
            clear: both;
        }

        .head
        {
            float: left;
            display: block;
            width: 100%;
        }

        .box
        {
            float: left;
            width: 100%;
            background-color: #FFF3CE;
            padding: 5px;
            border: #FFC928 1px solid;
        }

        .chat
        {
            padding: 5px;
            background-color: #BFBFBF;
            border: 1px solid #333;
            float: left;
            margin-right: 10px;
            font-size: 10px;
        }
         small
        {
            font-size: 8px;
        }

        h2
        {
            margin:0;
            color: #333;
            float: left;
        }
        a
        {
            font-size: 12px;
            text-decoration: none;
        }
        #red
        {
            color: #f00;
            width: 100%;
            font-size: 12px;
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <div class="box">
            <div class="head">
                <h2>You are BOB</h2><br>
                <small>Open links in two different browsers</small>
            </div>
            <div class="chat">
                <a href="<?=base_url()?>welcome/chat/Bob/Robert">Chat(You with Robert)</a><br>
                Link: <input type="text" name="" readonly="readonly" value="<?=base_url()?>welcome/chat/Bob/Robert"><br>

                <small>Open in one browser</small>
            </div>
            <div class="chat">
                <a href="<?=base_url()?>welcome/chat/Robert/Bob">Chat(Robert with You)</a><br>
                Link: <input type="text" name="" readonly="readonly" value="<?=base_url()?>welcome/chat/Robert/Bob"><br>

                <small>Open in one browser</small>
            </div><br>

            <div id="red">There could me more than one instance because someone else might also view this demo at same time.</div>
        </div>
    </div>
</body>
</html>

You are BOB

Open links in two different browsers
Chat(You with Robert) Link: Open in one browser
Chat(Robert with You) Link: Open in another browser
There could me more than one instance because someone else might also view this demo at same time.

this would give an interface like the screenshot below

Selection_036.jpg.scaled500

Lets learn the things better.

in teh above code you would see links like

<?=base_url()?>welcome/chat/Bob/Robert

Which is actually the welcome controller function that takes two parameters

1) your username or name (no spaces ,no dots, no special characters)

2) other person (to whome u want to chat with) username or name (no spaces ,no dots, no special characters)

here is how the controller looks now with both index and chat functions

class Welcome extends CI_Controller {      
  public function index()    
   {         
        $this->load->view('startChat');     
   }          

   function chat($me, $you)   
   {
       $data['me'] = $me;       
      $data['you'] = $you;       
      $this->load->view('chatty', $data);   
    } 
}

As you see above i passed the parameters to the CHat function, that futher uses those parameters with the view "chatty".

The problem starts now, the original script used native php sessions, where as codeigniter uses its own session classes. SO what do we do?

simply set session with the name "username" as session variable.

<?php session_start(); 
$_SESSION['username'] = $me;  
//$me conatins your username, so just save it in native session variable

Your complete "chatty.php" view would look like

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

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/loose.dtd" >

<html>
<head>
<title>Sample Chat Application</title>
<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="<?=base_url()?>chat/css/chat.css" />
<link type="text/css" rel="stylesheet" media="all" href="<?=base_url()?>chat/css/screen.css" />
<script type="text/javascript" src="<?=base_url()?>chat/js/jquery.js"></script>
<script type="text/javascript" src="<?=base_url()?>chat/js/chat.js"></script>
<!--[if lte IE 7]>
<link type="text/css" rel="stylesheet" media="all" href="<?=base_url()?>chat/css/screen_ie.css" />
<![endif]-->

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

<a href="javascript:void(0)" onclick="javascript:chatWith('<?=$you?>')">Chat With <?=$you?></a>

<!-- YOUR BODY HERE -->

</div>

</body>
</html>
Selection_037

Clicking the link would open a chat on right bottom like gmail/facebook

Selection_038.jpg.scaled500

Now let use see what really happens

when u click the link, a function called "chatWith" defined in chat.js gets triggered.

The function takes one parameter, the username of the other person, this function creates the chatbox and shows the interface

rest all is magic.

Please make sure that you do not use names with spaces and special characters. I also created the video explaing the mamoth. Please view in HD.

Download Zip Package

The code is free, change it as u like, suggestions are always welcomed.

UPDATE: 12th October 2015

So it got to know this chat does not work and names show up as undefined. The code has been udpated. It was due to old jquery file and deprecation of mysql functions.

Change in code made were in file CHAT.PHP

@session_start();
global $dbh;
$dbh = @mysql_connect(DBPATH,DBUSER,DBPASS); // addded a @ to suppress error
@mysql_selectdb(DBNAME,$dbh); // added a @ to suppress error

NOTE: this code still uses deprecated mysql functions.

Thank you for keeping calm.