How to Easily Make a PHP Chat Application

Today I will tell you about creating simple Chat application using our existing login system. This will be useful and most simple solution. We will able to chat with our logged members. We will use database to store messages.

Here is a sample and package:

Live Demo

[sociallocker]

download in package

[/sociallocker]


Now please download the example files and lets start coding!


Step 1. HTML

As usual, we start with the HTML.

This main chat window.

index.html

1 <frameset rows="65%,35%" framespacing="1" frameborder="yes" border="1" bordercolor="#FF0000">
2     <frame src="messages.php" name="main_frame">
3     <frame src="main.php" name="login_frame" scrolling="no" noresize target="middle">
4 </frameset>

This is login form code.

login_form.html

1 <link type="text/css" rel="stylesheet" href="styles.css" />
2 <form class="login_form" method="post" action="main.php">
3  <div>Username: <input type="text" name="username" /></div>
4  <div>Password: <input type="password" name="password" /></div>
5  <div><input type="submit" value="Login" name="Login" /></div>
6 </form>
7 <div>You can use username "User1" or "User2" or "User3" and password "qwerty" to login in system</div>

Here are new 3 template files to chat (2 to messages box and 1 to send message form):

chat_begin.html

1 <link type="text/css" rel="stylesheet" href="styles.css" />
2 <div class="chat_main">
3  <h3>Chat</h3>

chat_end.html

1 </div>

chat_input.html

1 <link type="text/css" rel="stylesheet" href="styles.css" />
2 <form class="submit_form" method="post" action="main.php">
3  <div><input type="text" name="s_message" /><input type="submit" value="Say" name="s_say" /></div>
4 </form>
5 <div>You can type anything in chat</div>

Step 2. CSS

Here are used CSS styles.

styles.css

01 .login_form {
02  border1px solid #AAA;
03  padding:10px;
04 }
05 h3 {margin-top:3px;}
06 .chat_main {
07  border:1px solid #AAA;
08  -moz-box-shadow:0 0 10px #ccc;
09  -webkit-box-shadow: 0 0 10px #ccc;
10  width:350px;
11  padding:10px;
12  background:#f3f3f3;
13 }
14 .message {
15  border:1px solid #AAA;
16  margin:4px;
17  padding:5px;
18  -moz-border-radius:7px;
19  -webkit-border-radius:7px;
20  background:#ffffff;
21 }
22 .textf {
23 -moz-box-shadow:0 0 10px #CCCCCC;
24 -webkit-box-shadow:0 0 10px #CCCCCC;
25 border:1px solid #CCCCCC;
26 height:40px;
27 }
28 .submit {
29 -moz-border-radius:7px;
30 -webkit-border-radius:7px;
31 background:#F3F3F3;
32 border:1px solid #CCCCCC;
33 font-size:16px;
34 font-weight:bold;
35 height:35px;
36 margin-left:10px;
37 padding:5px;
38 }
39 .message span {
40  font-size:10px;
41  color:#888;
42  margin-left:10px;
43 }
44 .submit_form {
45  margin:10px 0px;
46 }

Step 3. SQL

We will need to execute next SQL in our database.

1 CREATE TABLE `s_chat_messages` (
2 `id` INT(11) NOT NULL AUTO_INCREMENT ,
3 `userVARCHAR(255) NOT NULL ,
4 `message` VARCHAR(255) NOT NULL ,
5 `whenINT(11) NOT NULL ,
6 PRIMARY KEY (`id`)
7 ) ENGINE=MyISAM DEFAULT CHARSET=utf8;

Step 4. PHP

As you remember – we already had ready easy authentication system. I moved it to external library file (inc/login.inc.php). This will useful for us – now code more structured and it comfortable to use in different places of code.

After I created new library to work with chat (inc/chat.inc.php). This class have next functions:

acceptMessages – function accepts sent messages and saves them in database table

getMessages – returns list of recent 15 messages

Then I created two php files: messages.php and main.php. First file generates list of recent messages. It refreshes the list each 5 seconds (it is enough to our chat). Second file generates a login form and one text input field for the chat. After we login, we can use this field to post messages in the chat.

Ok, here are all used PHP files:

main.php

01 <?php
02 // set error reporting level
03 if (version_compare(phpversion(), "5.3.0"">=") == 1)
04  error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
05 else
06  error_reporting(E_ALL & ~E_NOTICE);
07 require_once('inc/login.inc.php');
08 require_once('inc/chat.inc.php');
09 // initialization of login system and generation code
10 $oSimpleLoginSystem new SimpleLoginSystem();
11 $oSimpleChat new SimpleChat();
12 // draw login box
13 echo $oSimpleLoginSystem->getLoginBox();
14 // draw chat application
15 $sChatResult 'Need login before using';
16 if ($_COOKIE['member_name'] && $_COOKIE['member_pass']) {
17  if ($oSimpleLoginSystem->check_login($_COOKIE['member_name'], $_COOKIE['member_pass'])) {
18  $sChatResult $oSimpleChat->acceptMessages();
19  }
20 }
21 echo $sChatResult;
22 ?>

messages.php

1 <meta http-equiv="refresh" content="5">
2 <?php
3 require_once('inc/chat.inc.php');
4 $oSimpleChat new SimpleChat();
5 echo $oSimpleChat->getMessages();
6 ?>

inc/chat.inc.php

01 <?php
02 // simple chat class
03 class SimpleChat {
04     // DB variables
05     var $sDbName;
06     var $sDbUser;
07     var $sDbPass;
08     // constructor
09     function SimpleChat() {
10         //mysql_connect("localhost","username","password");
11         $this->sDbName = 'database_name';
12         $this->sDbUser = 'username';
13         $this->sDbPass = 'password';
14     }
15     // adding to DB table posted message
16     function acceptMessages() {
17         if ($_COOKIE['member_name']) {
18             if(isset($_POST['s_say']) && $_POST['s_message']) {
19                 $sUsername $_COOKIE['member_name'];
20                 //the host, name, and password for your mysql
21                 $vLink = mysql_connect("localhost"$this->sDbUser, $this->sDbPass);
22                 //select the database
23                 mysql_select_db($this->sDbName);
24                 $sMessage = mysql_real_escape_string($_POST['s_message']);
25                 if ($sMessage != '') {
26                     mysql_query("INSERT INTO `s_chat_messages` SET `user`='{$sUsername}', `message`='{$sMessage}', `when`=UNIX_TIMESTAMP()");
27                 }
28                 mysql_close($vLink);
29             }
30         }
31         ob_start();
32         require_once('chat_input.html');
33         $sShoutboxForm = ob_get_clean();
34         return $sShoutboxForm;
35     }
36     function getMessages() {
37         $vLink = mysql_connect("localhost"$this->sDbUser, $this->sDbPass);
38         //select the database
39         mysql_select_db($this->sDbName);
40         //returning the last 15 messages
41         $vRes = mysql_query("SELECT * FROM `s_chat_messages` ORDER BY `id` ASC LIMIT 15");
42         $sMessages '';
43         // collecting list of messages
44         if ($vRes) {
45             while($aMessages = mysql_fetch_array($vRes)) {
46                 $sWhen date("H:i:s"$aMessages['when']);
47                 $sMessages .= '<div class="message">' $aMessages['user'] . ': ' $aMessages['message'] . '<span>(' $sWhen ')</span></div>';
48             }
49         else {
50             $sMessages 'DB error, create SQL table before';
51         }
52         mysql_close($vLink);
53         ob_start();
54         require_once('chat_begin.html');
55         echo $sMessages;
56         require_once('chat_end.html');
57         return ob_get_clean();
58     }
59 }
60 ?>

inc/login.inc.php

01 <?
02 // class SimpleLoginSystem
03 class SimpleLoginSystem {
04     // variables
05     var $aExistedMembers// Existed members array
06     // constructor
07     function SimpleLoginSystem() {
08         $this->aExistedMembers = array(
09             'User1' => 'd8578edf8458ce06fbc5bb76a58c5ca4',
10             'User2' => 'd8578edf8458ce06fbc5bb76a58c5ca4',
11             'User3' => 'd8578edf8458ce06fbc5bb76a58c5ca4'
12         );
13     }
14     function getLoginBox() {
15         ob_start();
16         require_once('login_form.html');
17         $sLoginForm = ob_get_clean();
18         $sLogoutForm '<a href="'.$_SERVER['PHP_SELF'].'?logout=1">logout</a>';
19         if ((int)$_REQUEST['logout'] == 1) {
20             if (isset($_COOKIE['member_name']) && isset($_COOKIE['member_pass']))
21                 $this->simple_logout();
22         }
23         if ($_REQUEST['username'] && $_REQUEST['password']) {
24             if ($this->check_login($_REQUEST['username'], MD5($_REQUEST['password']))) {
25                 $this->simple_login($_REQUEST['username'], $_REQUEST['password']);
26                 return 'Hello ' $_REQUEST['username'] . '! ' $sLogoutForm;
27             else {
28                 return 'Username or Password is incorrect' $sLoginForm;
29             }
30         else {
31             if ($_COOKIE['member_name'] && $_COOKIE['member_pass']) {
32                 if ($this->check_login($_COOKIE['member_name'], $_COOKIE['member_pass'])) {
33                     return 'Hello ' $_COOKIE['member_name'] . '! ' $sLogoutForm;
34                 }
35             }
36             return $sLoginForm;
37         }
38     }
39     function simple_login($sName$sPass) {
40         $this->simple_logout();
41         $sMd5Password = MD5($sPass);
42         $iCookieTime = time() + 24*60*60*30;
43         setcookie("member_name"$sName$iCookieTime'/');
44         $_COOKIE['member_name'] = $sName;
45         setcookie("member_pass"$sMd5Password$iCookieTime'/');
46         $_COOKIE['member_pass'] = $sMd5Password;
47     }
48     function simple_logout() {
49         setcookie('member_name''', time() - 96 * 3600, '/');
50         setcookie('member_pass''', time() - 96 * 3600, '/');
51         unset($_COOKIE['member_name']);
52         unset($_COOKIE['member_pass']);
53     }
54     function check_login($sName$sPass) {
55         return ($this->aExistedMembers[$sName] == $sPass);
56     }
57 }
58 ?>

View Live Demo of our sample


Conclusion

I described how to make easy chat application based on PHP and MySQL. You can use this material to create own scripts into your startups. Good luck!