CodeIgniter Chat example


How to creating and integrate gmail, facebook like chat system to the CodeIgniter system or web site.In this article is describing step by step how to integrate simple chat process into the CodeIgniter.

CodeIgniter Chat example Features

  • Multiple chatting
  • Using JQuery Ajax
  • Display notifications by changing colors
  • Displays Sent time after 3 minutes of inactivity
  • Basically similar to Gmail, Facebook like chat box
  • Auto-resize of text input box
  • Minimize and close chat boxes

Browser Compatibility

1. Firefox 2+
2. Chrome
3. Internet Explorer 6+
4. Safari 2+
5. Opera 9+

CodeIgniter Facebook like ajax Live Chat Plugin Version 2

CodeIgniter Facebook like ajax Live Chat Plugin Version 2

How to create chat process


1-First install fresh codeigniter into your localhost or web server.You can learn how to install codeigniter by it’s official web site.

2-Open the config file(application/config/config.php) and put your server and database details there.
Also need to as TRUE.

And coockie path ,


1-Go to the phpmyadmin, run this tables there.

chat table

users table

Download full database from here.


1-Download this chat.js Javascript file and keep it in the script folder named as js(application/js).
Open that file and replace your site url instead of the “http://localhost/CodeIgniter/”.There are 4 places.

Download chat.js file from here.


2-Also you need to put these jquery.js files there.

3-Then download these 3 css files and keep those in the css folder(application/css).

Download css files(3 KB)

File structure.
CodeIgniter-chat css files


1-Create a file to display online users.I’m do this,

-application/views/chat/userList.php (view file)
userList.php file structure

-application/controllers/chat.php (controller file)

chat.php controller file structure

2-Download this chat.php file to process the chat, and put it in the application/views/chat/
Download chat.php file from here.

Open that file and put the server, database details there and save it.

3-Go to the model folder and create file named users_model.php

My file structure like this.
codeigniter chat example folder_structure


Chat by Chris:

Chat by Sumith

Chat history saved in the table

chat history

That’s only.

View CodeIgniter Chat example Demo

Go to the new page and wait 5 seconds, then click “SKIP AD” button of the top right corner.Then you can view demo.

Full source code containing with users login and logout process.

Download Full CodeIgniter Chat Example(2.6 MiB)

Want this freebie? Enter your email and get it now!

Simply enter your email address and the download link will be sent right to your inbox.


About Author

Sumith Harshan is the Web Engineer Specializes in Java Script, JQuery, HTML4/5, CSS2/3, PHP, CodeIgniter, CakePHP, J2SE, J2EE, XML, Hacking & Security, Mobile Interface Developing, Magento, Wordpress, Joomla, Drupal,PHPBB,Facebook App Developing and Open cart...etc.


  1. It was not working for us. there is no db file and corect file structure and html. Please provide us remaining or full code

  2. It was not working, Plase help me, how to confige routes file to first run website (it’s default: $route[‘default_controller’] = “welcome”; ),
    (tree folder following)  ,

    • -Set the main page name(welcome) in the routes.php files set as follows.
      $route[‘default_controller’] = “welcome”;
      Welcome is the controller name.So you need to set correct view file path in that main welcome controller .
      EX:- view file name – welcome.php. This is locate in the main view folder(you can change it.).Then set this path as follows in the welcome controller.(welcome.php)
      public function index()

      routes.php ——-> $route[‘default_controller’] = “welcome”;

      welcome.php comtroller file ———->
      public function index()

      Set these configurations in the config.php file.
      $config[‘hostname’] = “localhost”;
      $config[‘db_username’] = “root”;
      $config[‘db_password’] = “123456”;
      $config[‘db’] = “codeigniter_demo”;

      create chat table and run the site as http://localhost/demoChat/welcome/

      •  file welcome in controller: public function index()
        file config/database.php
        $db[‘default’][‘hostname’] = ‘localhost’;
        $db[‘default’][‘username’] = ‘root’;
        $db[‘default’][‘password’] = ”;
        $db[‘default’][‘database’] = ‘zerostr_zero’;

        when i run this site http://localhost/demoChat/ then display error:

        A PHP Error was encountered

        Severity: Notice
        Message: Undefined variable: UsersList
        Filename: chat/users_list.php
        Line Number: 51

        Fatal error: Call to a member function result() on a non-object in C:xampphtdocsdemoChatapplicationviewschatusers_list.php on line 51

        User Id
        User Name
        …….please help me,
        Thanks Advanced/

        • You need to define this variable in the current controller.This is a basic error in the codeigniter. You can refer the codeigniter official site to get and display values from controller to view.So in here, need to get current users name list from controller and display it in the view page.
          function index()


          //Get all users list using user_model
          $this->outputData[‘UsersList’] = $this->user_model->getUsers();

          //Load the users list view

          In the users_list.php file getting this variable values as an array and display it.
          foreach($UsersList->result() as $Users){
          Users names here


          •  Thank you very much for your helps,I have run successful website.I tried to design the table users and roles for testing your program, but did not succeed.can you send me the database structure of the table users and roles.I thank you for that.p / s: I am a newbie.        You do not laugh.

          •  Question 1: I changed Paths in js/chat.js
     to   http://localhost/demoChat/applicationviews/chat/chat.php?action=   .
              But not active. I run website and after click to link username (on display user_list file) then nothing appear.

            Question 2:
            in CodeIgniter then Is it allow character like:  “chat.php?action= …”  in Ajax Url variable,



          • hi thanks! for the code

            it works fine on my WAMP – localhost , BUT when i tried on server (ONLINE) –> all worked well but when i click on anyone’s name then NOTHING happen.

            I can see whether users are “active”/”inactive” but the problem in chat pop-up (may be in jquery), so please help.

            thanks in advanced.

          • -First you need to change all urls I have told as in this article(specially chat.js file,chat.php file).
            -You need to put jquery file and then its path as I said.Then try it.

            -Check whether CI is allow to direct path access in the server.If not remove the all codes in the application/.htaccess file.(not suitable) . Or you can give correct file paths and allow to access them.


          • thanks! it worked….but

            when i upload them on my server (online) everything works fine but:-

            1. it says “undefined” in place of my name ($from)
            (check attached jpeg)
            2. also there is no entry in database.

            also i changed all the urls in chat.js and also i have correct entries of my database in view/chat.php.

            plz reply

            thanks in advance

          • This is happening not saving codeigniter session properly.Check your session variables and check it’s username.When session username is empty, then you can see this as “undefined” . You can see in the chat table, from field is empty.That is because of this issue.
            Then check config.php file for following configurations.

            $config[‘sess_cookie_name’] = ‘ci_session’;
            $config[‘sess_expiration’] = 7200;
            $config[‘sess_expire_on_close’] = FALSE;
            $config[‘sess_encrypt_cookie’] = TRUE;
            $config[‘sess_use_database’] = FALSE;
            $config[‘sess_table_name’] = ‘ci_sessions’;
            $config[‘sess_match_ip’] = FALSE;
            $config[‘sess_match_useragent’] = TRUE;
            $config[‘sess_time_to_update’] = 300;

            In the above, $config[‘sess_use_database’] = FALSE; Then session data not saving. Keep it FALSE.


          • thanks for your quick reply!

            first of all there is no problem in your code but i have to integrate it with my website which requires login.

            There is no problem in chat pop and also now it shows user name instead of “undefined”. Also now all the chat entries are saved in DB.

            But there is only one way communication i.e. although both can send the chat but only one can receive the chat.

            i know there is no problem in your code and there is some mismatch when I integrate your code with my website. I really appreciate your code and I know there is some slight problem on my side but I cant find that loophole.

            Waiting for your reply.

            Thanks in advanced.

          • Hello I have same problem with CI and the SESSIONS, “Undefined !” Do you have a solution ? please 🙂

          • Check the set session start in the users view file.

            $_SESSION[‘username’] = $this->session->userdata(‘username’);

            Check the config.php file for following details are same as follows.
            $config[‘sess_cookie_name’] = ‘ci_session’;
            $config[‘sess_expiration’] = 7200;
            $config[‘sess_expire_on_close’] = FALSE;
            $config[‘sess_encrypt_cookie’] = TRUE;
            $config[‘sess_use_database’] = FALSE;
            $config[‘sess_table_name’] = ‘ci_sessions’;
            $config[‘sess_match_ip’] = FALSE;
            $config[‘sess_match_useragent’] = TRUE;
            $config[‘sess_time_to_update’] = 300;


          • Hi,
            application/views/chat/chat.php –> add “@” mark before the mysql_query as follows.
            Hope this work and this is may be in the wamp new server.

          • it’s not working… i need the Full source code containing with users login and logout process. i try to download it but i receive nothing in my email and (thanks alot )

          • Every about 2 seconds, checking chat data via ajax. It is going like :-http://localhost/CodeIgniter/application/views/chat/chat.php?action=chatheartbeat ………… etc.

            First you need to change all urls I have told as in this article.
            You need to put jquery file and then its path as I said.Then try it.


  3. Fatal error: Class ‘Controller’ not found in D:xampphtdocssearchapplicationcontrollerschat.php on line 15

  4. Fatal error: Class ‘Controller’ not found in D:xampphtdocssearchapplicationcontrollerschat.php on line 15

    • is my controller name.So you can put your own controller name.The defalut controller name is CI_Controller . You can try like this.

      class Chat extends Controller
      class Chat extends CI_Controller


  5. Thank you very much !

    I put and run full source code.Worked chat process very well. Demo is perfect.Can I drag the chat boxes?
    I find CI chat example every where. Finally I found correct place.You saved my time.Thanks again!

  6. Thanks for the code… I implemented everything and worked like a charm.. But, I have one issue, while chatting, if I close the chat box (no logout), and someone sends chat, the chat box opens, thats fine.. but, all chat message shows up (there is already few text in chat box, and seems, that already chat message again comes from database).

    • That displaying chat history is normal process of the chat.For a example, you know automatically load chat history in the facebook chat box/gmail.

      You can try to comment or modify views/chat/chat.php file, line 151 as follows.
      foreach ($_SESSION[‘openChatBoxes’] as $chatbox => $void) {
      // $items .= chatBoxSession($chatbox);

      Then not loading chat history.


  7. A Database Error Occurred

    Error Number: 1046

    No database selected

    SELECT ci_users.user_id, ci_users.user_name, ci_users.user_email,
    FROM (ci_users)
    WHERE ci_users.user_id = 0
    ORDER BY ci_users.user_id asc

    Filename: C:wampwwwcodeignitersystemdatabaseDB_driver.php

    Line Number: 330

      • I am also seeing the same error,database configuration looks fine.

        A Database Error Occurred

        Error Number: 1046

        No database selected

        SELECT ci_users.user_id, ci_users.user_name, ci_users.user_email, FROM (ci_users) WHERE ci_users.user_id = 0 ORDER BY ci_users.user_id asc

        Filename: C:wampwwwgoodchatsystemdatabaseDB_driver.php

        Line Number: 330

        • I forgot to tell to check same database details in the app/views/chat/chat.php file :
          define (‘DBPATH’,’localhost’);
          define (‘DBUSER’,’root’);
          define (‘DBPASS’,”);
          define (‘DBNAME’,’codeigniter’);


          • Another observation is DB_driver.php also requires similar DB details, looks like its missing there as well.

            Unfortunately, for me even updating this file is also not helping !!!

          • Better way is configure the application codeigniter without process of chat files.It think there are/is simple mistake in your codeigniter application. If no errors, then add your chat files and check it. I tested this chat process more than 10 times without any errors.So try to follow above instructions.


          • If I keep the default database.php values such as

            $db[‘default’][‘hostname’] = $CI->config->item(‘hostname’);

            $db[‘default’][‘username’] = $CI->config->item(‘db_username’);

            $db[‘default’][‘password’] = $CI->config->item(‘db_password’);

            $db[‘default’][‘database’] = $CI->config->item(‘db’);

            it works fine.

            Should’nt these database values point to my DB details instead?

          • Yet another obsevation is that on the webserver I see no chat messages are displayed nor sent, however chat messages gets recorded in database ( chat table), any idea whats going wrong here?


  8. Thank u very much for the code….
    when i integrate it with my code, the entire chat history automatically appended to chat window in an interval. will you please help me to correct that.

  9. Aleena Joseph on

    Thank u very much for the code….

    when i integrate it with my code, the entire chat history automatically
    appended to chat window in an interval. will you please help me to
    correct that.

    • That feature is normal process of the chat.For a example, you know automatically load chat history in the facebook chat box.
      You can try to comment or modify views/chat/chat.php file, line 151 as follows.
      foreach ($_SESSION[‘openChatBoxes’] as $chatbox => $void) {
      // $items .= chatBoxSession($chatbox);

      Then not loading chat history.


      • Aleena Joseph on

        In my code, I reload the user list using ajax for find online users. so userlist automatically refreshed in every 5 sec. At that time chat history also again appended with above history. Actually I want chat history but in my code it repeat in every 5 sec.

        When I try to solve this ,I close and again open chat box in checkChatBoxInputKey() and in chatHeartbeat() before appending the history. but the problem still arise when I receive msg from another window. Will u pls help me…. And Thanks for the reply

  10. Hi Sumith Harshan, I can’t download you chatting script.When click on the “Download Full Codeigniter Chat Example ” button ,its redirect me another page.
    Please help me,or send me all script on my mail id “”.
    Thanking You


    • Hi dear,
      After clicked Download button, it goes to the new page.After 5 seconds you can see “SKIP AD” yellow color button top right corner in the page.Click on it.Then you can download the full source code.


  11. hi i’m not able to download the source code..when i click on your download link it takes me to the ad fly page which is just blank and i’ve got nowhere to go from there your help would be greatly appreciated. Thanks in advance

  12. your code not fill history in chatbox when we open it first time like facebook chatbox fill the previous chat i changed in jquery and customised it but though it not show me history..any suggestion would be appreciate..Thanks.

    • Hello saghar.
      Can you tell me what are the missed functions on that file. Because the download source code is a copy of the demo files. I checked by comparing them. No any missed functions.


  13. hi I encounter this error everytime i click the lUsers Login link.

    “Fatal error: Call to a member function num_rows() on a non-object in C:xampphtdocschichatapplicationmodelsusers_model.php on line 69”


    • Hi,

      This is related to the getLoggedInUser() function in this model.In there, checking logged users details and return it.It is getting data from the session. Did you check the session is working fine and config settings are correct or not?

      If everything are ok, then simply check if session user id empty or not in that function.
      function getLoggedInUser()

      $user = ”;

      if($this->session->userdata(‘user_id’) !=”) {
      $condition = array(‘ci_users.user_id’=>$this->session->userdata(‘user_id’));
      $fields = ‘ci_users.user_id,ci_users.user_name,ci_users.user_email,’;

      $query = $this->getUsers($condition,$fields);

      $user = $query->row();

      return $user;


  14. I can’t get the chat room while clicking on the username. I am using jquery 1.9.1, is this the problem?

    • Hi. Thanks for the reading my post.When you clicked on the username it call to the chatWith(chatuser) function in the chat.js file. It is getting the user name and do the chat process. I added to that file jQuery.noConflict() function.

      First check the user name is loaded into that function as following.

      onClick=”javascript:chatWith(‘user_name; ?>’);”

      Then add jQuery.noConflict() function top of the file.

      Let me know your response.


  15. Call to a member function where() on a non-object in C:wampwwwchatnewapplicationmodelsusers_model.php on line 31

    showing this error.. how can i correct it?

      • Hi,
        can you check when you call to function getUsers() you passed the where condition to it?

        If correctly added then add the following code after this code.


        need to add after here.
        function getUsers($conditions=array(),$fields=”)


        When you add it look like this.

        function getUsers($conditions=array(),$fields=”)


        Save and run.


  16. hi sumit the download link not working. From where i can download the code

  17. Prince Mahendra Sharma on

    hello sumit…
    i need ur help…

    $config[‘sess_cookie_name’] = ‘ci_session’;
    $config[‘sess_expiration’] = 7200;
    $config[‘sess_expire_on_close’] = FALSE;
    $config[‘sess_encrypt_cookie’] = TRUE; // This must be TRUE
    $config[‘sess_use_database’] = FALSE; // This must be FALSE
    $config[‘sess_table_name’] = ‘ci_sessions’;
    $config[‘sess_match_ip’] = FALSE;
    $config[‘sess_match_useragent’] = TRUE;
    $config[‘sess_time_to_update’] = 300;

    if i want to keep $config[‘sess_use_database’] = FALSE;…… TRUE…….

    then what what to do ???

    Actually i need to save session data in database….
    right now i is showing undifined at the place of $from….
    plz reply

  18. yoga kumboro on

    hi smith, thanks 4 the code..
    I had the problem when implement your code:
    the page and chatbox work fine, but when I type some text & then send it nothing happend, no text appeared in the chatbox
    need ur help plz

  19. I did every thing perfectly according to you but i am not able to chat only chat window is open but not able to get massage and send massage

    • You can check response using firebug console when you are sending messages.If response url is not found check chat.js file relevant paths.Also check the db details , chat.php file db details too.


  20. yoga kumboro on

    I tried to combine your code with my application in my company, unfortunately my company using ms sql server.
    I strugled to change some part of your code in chat.php in views folder, but still failed.

    define (‘DBPATH’,’localhost’);
    define (‘DBUSER’,’root’);
    define (‘DBPASS’,”);
    define (‘DBNAME’,’codeigniter’);
    //$user_name = trim($this->session->userdata(‘username’));

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

    How could do this in ms sql server.


  21. I have given my email id, but i could not download. As it leads to some ad pages. please help to download.Thanks

  22. Dear Sumith Harshan

    I’ve read your article about facebook/gmail like chat.
    And I implemented succesfully on my localhost with original version of yours.
    But when I tried to modify your code to be my version, I seems so tricky.
    I got problem to access view from url inside Jquery chat.js.

    here’s some of mycode inside chat.js jquery :

    url: “http://localhost/system/application/views/reminder/chat.php?action=chatheartbeat”,
    cache: false,
    dataType: “json”,
    success: function(data) {

    I’ve debug this problem using firebugs, and try so many way including change :

    url: “http://localhost/system/application/views/reminder/chat.php?


    – url: “../system/application/views/reminder/chat.php?
    – url: “/chat.php?

    but still I didn’t succeed

    Please help, coz I’m getting crazy about this

  23. Hi there,,
    i have download copied and run your code but it didnt work….chat box appears when clicked to the username(CI_users) bt when msg is typed and clicked,msg dissapears and database has no messages saved..

  24. thanks Sumith script is working but i want to store the sender and receiver id in chat table can you help me how to make it?

  25. sir, this is the start page of this project when i click on the user login this error occur….. plz solve it sir

  26. i have a serious problem chat is open in chrome but when i tried to send chat it then it doesnt work and on sender name it appears undefiend

    • Hi,
      Check the jquery_cookie.js file is added to the header file/into your site.Also remember add jquery library file add top of the all js files.

      and THEN


  27. chat is excellent but i am getting problem , when chat is opened in
    different tab of same browser then not all window of chat is update
    when message recieved.

  28. Hi Sumith

    i want to download code but it’s not working and downloadable link not opening.


  29. chat name not have option for define desplay name and user it, if bother user have same name then who it work

  30. Vivek S Nair S on

    Hi Sir,
    Its awesome, but response time is high. how could I fix the response time. If I entered a message in the box it will appear only after some time. and it takes more time to reach to the other user.
    Please help me to find a solution for that.

  31. hai. i am already try this code. When i execute the code but i couldn’t get the userList display. Can you help me to solve this?

    • Hi,
      No users / empty the value of $listOfUsers in userList.php. It getting values from controller/chat.php line 22,23 as following.
      //Get all users
      $this->outputData[‘listOfUsers’] = $this->users_model->getUsers();

      So check that returning empty values.


      • thanks ! i am already solve the problem. But i met a new problem. When i click the name, the popup box did not appear. When i check the view source, it said that the page not found. Can you help me?

  32. hi sumith, can you explain how to change the url in chat.js? i dont understand how to do it. Anyone also can help me. please… 🙁

  33. Excuse me brother. I got problem with the jquery file? I download it from the jquery website. Seems the jquery fils isnt working. I really need your help.

  34. i m unable to Download Full CodeIgniter Chat Example.. the link send me on my email is not open the download page gives an error ..plz help meeeee to download this full source code..

  35. hi
    thank you for job !
    but i have many problems , and i want to help me plz 🙁 🙁 🙁 !
    first problem :
    when i login tow user ann and smith
    send message from smith to ann nothing disable in ann similar this images !
    twice problem :
    the name of Ann id disable as “undefined”
    pleas help me 🙂 !
    thanks alooooooooooooooooooooooooo0o0o0o0o0o0T !

      • Thanks for your fast reply, but i am talking about view/chat/chat.php file. so please help me on this, all queries in core php here therefore its not working to create session plz help me.

        • Chat.php controller. change there view name:-

          to:- $this->load->view(‘chat/chat’,$this->outputData);

          Note there this->load->view(‘viewfoldername/filename’,$this->outputData);

          • rahul kumar on

            now its showing this error when i chaged it to chat/chat

            A PHP Error was encountered

            Severity: Notice

            Message: Undefined index: action

            Filename: chat/chat.php

            Line Number: 34

      • sir i did’t using here userList in my project i just want to know how to
        use codeigniter session username in view/chat/chat.php . In db from
        field is going blank because of that please help me.

  36. Ketan Sangani on

    Your Code Works Fine..But if i logged out after 2 hours as set $config[‘sess_expiration’] = 7200;
    but still i appeared online..plzz help to solve this??

  37. Himasha Liyanage on

    hi sir i implemented your code and it doesnt show any online users.
    it just shows the column names.please help

    • hi,
      It’s in localhost or in the web server as live?
      Check the config file if correct,views/chat/chat.php for config details and chat controller.

      Check the email for info. I’ll send more details 2mrw.

        • Read these instructions carefully and double check the code.

          1-Check the controller/chat.php
          There you can see it’s fetching list of users from the model.
          Line 22,23

          //Get all users
          $this->outputData[‘listOfUsers’] = $this->users_model->getUsers();

          So check it’s >getUsers function in the models/users_model.php

          Make sure your users table name,column names are correctly placed there.
          If you did it correctly this function is returning the list of users.

          2-You can see the correct view is $this->load->view(‘chat/userList’,$this->outputData);

          You will see i got the lst of users from chat.php controller as following.

          foreach($listOfUsers->result() as $res)

          …….. etc.

          So in this loop is showing list of users.

          check there you added correct db details.

          check your file path there:-
          Line 224.
          url: “http://localhost/CodeIgniter/application/views/chat/chat.php?action=chatheartbeat”,

          Line 285

          Line 352

          Line 387
          url: “http://localhost/CodeIgniter/application/views/chat/chat.php?action=startchatsession”,

          Let me know if you have further questions.

          Thank you