Simple Chat System

Tutorials for php.

Simple Chat System

Postby Mortisimus on Sat Aug 30, 2008 5:18 pm

Ok, in this tutorial I will show you how to create a very basic chat system.

First we set up the database.
Code: Select all
CREATE TABLE chat (
id INT(11) AUTO_INCREMENT NOT NULL,
username VARCHAR(70) NOT NULL,
date DATETIME NOT NULL,
message TEXT NOT NULL
);

We create 4 columns. The ID, the username, the date and the message. We also need a config file that will connect to the database.

config.php
Code: Select all
<?php
DEFINE ('DB_USER', 'username'); //This is your database username
DEFINE ('DB_PASSWORD', 'password'); //This is your database password
DEFINE ('DB_HOST', 'localhost'); //Databse host, this is nearly always localhost
DEFINE ('DB_NAME', 'db_name'); //Your database name

$db = @mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to MySQL: ' . mysql_error());
@mysql_select_db (DB_NAME) OR die('Could not select the database: ' . mysql_error() );
?>

We define all the values for the database and then see if we can connect, and if not we show the error.

EDIT: The old tutorial was buggy and didn't work very well, here is the new one.

chat.php
Code: Select all
<?php
session_start();
include("config.php");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Chat Example</title>
<script type="text/javascript">
function createRequestObject() {
   var ro;
   var browser = navigator.appName;
   if(browser == "Microsoft Internet Explorer"){
       ro = new ActiveXObject("Microsoft.XMLHTTP");
   }else{
       ro = new XMLHttpRequest();
   }
   return ro;
}
var http = createRequestObject();

// This is the action within the page.
// initial is a paramter we need to pass to the PHP script
function runChat(name, msg) {
   http.open('get', 'chat.php?do=msg&name='+name+'&message='+msg);
   // Define a handler for the request
   http.onreadystatechange = handleResponse;
   http.send(null);
   document.form1.name.value='<?php echo $_SESSION['user']; ?>';
   document.form1.message.value='';
}
function handleResponse() {
   if(http.readyState == 4){
       var response = http.responseText;
       document.getElementById('response').innerHTML = 'message added!';
   }
}
</script>
</head>

<body>
<?php
if(isset($_GET['do'])){
       if(empty($_GET['name'])){
            echo "Enter a name";
        }
        elseif(empty($_GET['message'])){
            echo "Please enter a message";
        }
        else
        {
            // no problems
            $name = htmlentities(strip_tags(htmlspecialchars(mysql_escape_string($_GET['name']))));
            $msg = htmlentities(strip_tags(htmlspecialchars(mysql_escape_string($_GET['message']))));
            if(empty($_SESSION['user'])){
                $_SESSION['user'] = $name;
            }

            $q = @mysql_query("INSERT INTO chat (username, date, message) VALUES ('$name', NOW(), '$msg')");
            if(!$q){
              echo "MySQL Error: " . mysql_error();
            }
        }
}
else
{
?>
    <iframe src="read.php" scrolling="yes" width="700" height="600" frameborder="1">Please enable iframe support.</iframe>
   <div id="response"></div>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="form1">
    Your Name: <input type="text" size="30" name="name" value="<?php echo $_SESSION['user']; ?>" /><br />
    Your Message: <textarea name="message"></textarea><br />
    <input type="button" name="submit" value="Submit" onclick="javascript: runChat(document.form1.name.value, document.form1.message.value);" />
    </form>
    <?php
}
?>
</body>
</html>


In this, we create a function that uses a javascript http request object (which updates the page without reloading) and when the function is called, we pass the paramaters for the name and message to be inserted into the database because it runs the page chat.php?do=msg&name=whatever&message=whatever. Then we check if these values are in the url and if they are we insert the data to the database, if not we show the form and the chat box.

read.php
Code: Select all
  <?php
include("config.php");
  ?>
    <html>
    <head>
    <title></title>
    <meta http-equiv="refresh" content="5" />
    </head>

    <body>
   <div style="position:absolute; bottom:0; width:100%;">
<?php
// here is the other main page of the code
$query = @mysql_query("SELECT id, username, message, DATE_FORMAT(date, '%M %d, %Y') as md FROM chat ORDER BY id ASC LIMIT 50");
if($query){
// can select data, read it
while($row = mysql_fetch_array($query, MYSQL_ASSOC)){
echo $row['md'] . " - " . $row['username'] . ": " . $row['message'] . "<br />\n";
}
}
else
{
echo "Could not select messages.<br />";
echo mysql_error();
}
?>
   </div>
    </body>
    </html>


This page is essentially the same as before, get the 50 most recent messages and echo them. The only difference is that we add a css bottom:0; rule so that when you see the iframe, the most recent messages will show at the bottom without you having to scroll down every time the page refreshes (every 5 seconds).

DEMO

Thanks
User avatar
Mortisimus
Site Admin
 
Posts: 21
Joined: Mon Aug 25, 2008 6:04 pm

Re: Simple Chat System

Postby Paul on Fri Nov 07, 2008 6:23 pm

newbie here

i am currently using a user login script and is it possible if a member signs in and goes to the chat page and it shows hes name and he just types a message instead of typing hes name all the time
Paul
Newbie
 
Posts: 1
Joined: Fri Nov 07, 2008 6:20 pm

Re: Simple Chat System

Postby Mortisimus on Sat Nov 08, 2008 4:58 pm

Hi Paul, yes this is possible. Just find on your page where the html form is - this:
Code: Select all
   <div id="response"></div>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="form1">
    Your Name: <input type="text" size="30" name="name" value="<?php echo $_SESSION['user']; ?>" /><br />
    Your Message: <textarea name="message"></textarea><br />
    <input type="button" name="submit" value="Submit" onclick="javascript: runChat(document.form1.name.value, document.form1.message.value);" />
    </form>


And replace it with this (assuming the your login sytem is session based, the session $_SESSION['username'] would hold the value for the username.):
Code: Select all
   <div id="response"></div>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="form1">
   Your Name:
   <?php
   if(isset($_SESSION['username'])){
      echo "<input type=\"hidden\" name=\"name\" value=\"" . $_SESSION['username'] . "\" />". $_SESSION['username'] ."<br />\n";
   }else{
      echo "<input type=\"text\" size=\"30\" name=\"name\" /><br />\n";
   }
   ?>
   
    Your Message: <textarea name="message"></textarea><br />
    <input type="button" name="submit" value="Submit" onclick="javascript: runChat(document.form1.name.value, document.form1.message.value);" />
    </form>


If your session variable is not $_SESSION['username'] then just change it to whatever holds the variable.

Thanks
User avatar
Mortisimus
Site Admin
 
Posts: 21
Joined: Mon Aug 25, 2008 6:04 pm


Return to PHP Tutorials

Who is online

Users browsing this forum: No registered users and 1 guest

cron