Hi, this will show u How to make a simple chat first:
We will do the database first:
init.php
CODE
<?php
session_start();
/*
* replace the parameters used here with the appropriate information
* for your system.
*/
$dbhandle = mysql_connect("sql208..com","b5_2615902","jer123");
mysql_select_db("b5_2615902_chat");
/*
* IMPORTANT: magic quotes are bad. Ideally, you should turn them off
* in your php.ini, but if you are unable to, the code below will fix
* the $_POST array for you.
*
* See http://www.php.net/manual/en/security.magicquotes.php
*
* If you aren't using prepared statements (mysqli, Pear:DB) or manually
* escaping every variable that goes into a query, you are asking to get
* pwned. For maximum portability, jenChat uses mysql_real_escape_string,
* but prepared statements are generally the way to go.
*
* If you didn't understand that last paragraph (or even if you
* did), read up on SQL Injection and why you need to worry about it.
*
* http://www.unixwiz.net/techtips/sql-injection.html
*
* OK, carry on
*/
if(get_magic_quotes_gpc()){
$_POST = array_map('stripslash', $_POST);
}
function stripslash($value){
if(is_array($value))
return array_map('stripslash', $value);
else
return stripslashes($value);
}
?>
First, the code
CODE
<?php
session_start();
starts the session
This is nessesary if u want to use a database to store information!!
Next, we need to connect!
CODE
/*
* replace the parameters used here with the appropriate information
* for your system.
*/
$dbhandle = mysql_connect("sql208..com","b5_2615902","jer123");
mysql_select_db("b5_2615902_chat");
This connects to the database.
The next part i will show the script, but not go into detail because it is a backup
CODE
if(get_magic_quotes_gpc()){
$_POST = array_map('stripslash', $_POST);
}
function stripslash($value){
if(is_array($value))
return array_map('stripslash', $value);
else
return stripslashes($value);
}
?>
That is init.php
ok, next we have login.php
CODE
<?php
require_once('init.php');
if($_GET['logout']){ //they are logging out
mysql_query("DELETE FROM jenChat_Users WHERE UserID = " . $_SESSION['jenChat_UserID']);
$_SESSION = array();
if(isset($_COOKIE[session_name()])){
setcookie(session_name(), '', 1, '/');
unset($_COOKIE[session_name()]);
}
session_destroy(); // To delete the old session file
header("Location: ./login.php");
exit;
}
if(sizeof($_POST)){
$expiretime = date("YmdHis", time() - 5);
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(preg_match('/^[_a-z0-9-]+$/i',$_POST['who'])){
$result = mysql_query("SELECT UserID FROM jenChat_Users WHERE UserName = '".mysql_real_escape_string($_POST['who'])."' AND LastUpdate > " . $expiretime);
if(!mysql_fetch_array($result)){
mysql_query("DELETE FROM jenChat_Users WHERE LastUpdate <= " .$expiretime);
mysql_query("DELETE FROM jenChat_Messages WHERE Posted <= " . $expiretime);
mysql_query("INSERT INTO jenChat_Users(UserName,LastUpdate) VALUES ('".mysql_real_escape_string($_POST['who'])."'," . date("YmdHis",time()).")");
$_SESSION['jenChat_UserID'] = mysql_insert_id();
$_SESSION['jenChat_Prevtime'] = date("YmdHis",time());
header("Location: ./chat.php");
exit;
}
else
$error = "A user with the same handle is currently in the chat room. Please try a different handle.";
}
else
$error = "Handles may only contain letters, numbers, hyphens and dashes.";
}
else
$error = "You must enter a handle (screen name) to enter the chat room.";
}
?>
<!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" lang="en-US" xml:lang="en-US">
<head>
<title>jenChat</title>
</head>
<body>
<h1>jenChat</h1>
<form class="grid" method="post" action="./login.php">
Login<br>
<label for="who">Handle: </label><input type="text" id="who" name="who" value="<? echo htmlspecialchars($_POST['who']) ?>" />
<input type="submit" value="Join Chat" class="submit" />
</form>
<p class="error">
<? echo htmlspecialchars($error); ?>
</p>
</body>
</html>
That is the full code.
Here is the explanation
CODE
<?php
require_once('init.php');
That says that U MUST have the file init.php to work.
CODE
if($_GET['logout']){ //they are logging out
mysql_query("DELETE FROM jenChat_Users WHERE UserID = " . $_SESSION['jenChat_UserID']);
$_SESSION = array();
if(isset($_COOKIE[session_name()])){
setcookie(session_name(), '', 1, '/');
unset($_COOKIE[session_name()]);
}
session_destroy(); // To delete the old session file
header("Location: ./login.php");
exit;
}
That says if u are logging off, delete from mysql table and destroy cookies
next, the login.
CODE
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(preg_match('/^[_a-z0-9-]+$/i',$_POST['who'])){
$result = mysql_query("SELECT UserID FROM jenChat_Users WHERE UserName = '".mysql_real_escape_string($_POST['who'])."' AND LastUpdate > " . $expiretime);
if(!mysql_fetch_array($result)){
mysql_query("DELETE FROM jenChat_Users WHERE LastUpdate <= " .$expiretime);
mysql_query("DELETE FROM jenChat_Messages WHERE Posted <= " . $expiretime);
mysql_query("INSERT INTO jenChat_Users(UserName,LastUpdate) VALUES ('".mysql_real_escape_string($_POST['who'])."'," . date("YmdHis",time()).")");
$_SESSION['jenChat_UserID'] = mysql_insert_id();
$_SESSION['jenChat_Prevtime'] = date("YmdHis",time());
header("Location: ./chat.php");
exit;
}
else
$error = "A user with the same handle is currently in the chat room. Please try a different handle.";
}
else
$error = "Handles may only contain letters, numbers, hyphens and dashes.";
}
else
$error = "You must enter a handle (screen name) to enter the chat room.";
}
?>
This says that if the name is in use, u need to use a new name, invalid characters and blank name are not allowed.
The form.
CODE
<!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" lang="en-US" xml:lang="en-US">
<head>
<title>jenChat</title>
</head>
<body>
<h1>jenChat</h1>
<form class="grid" method="post" action="./login.php">
Login<br>
<label for="who">Handle: </label><input type="text" id="who" name="who" value="<? echo htmlspecialchars($_POST['who']) ?>" />
<input type="submit" value="Join Chat" class="submit" />
</form>
<p class="error">
<? echo htmlspecialchars($error); ?>
</p>
</body>
</html>
Don't need to explain this as this is php do i??
This is the actule code!!
CODE
<?php
session_start();
if(!$_SESSION['jenChat_UserID']){
header("Location: ./login.php");
exit;
}
else if(date("YmdHis",time() - 5) > $_SESSION['jenChat_Prevtime']){
header("Location: ./login.php?logout=true");
exit;
}
?><!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" lang="en-US" xml:lang="en-US">
<head>
<title>jenChat</title>
<style type="text/css">
#chatContents{height:300px; width:200px;}
</style>
<script type="text/javascript"><!--
var cDocument;
var cWindow;
window.onload = chat_init;
function chat_init(){
var chatContents = document.getElementById("chatContents");
//set up a reference to the window object of the IFRAME
if(window.frames && window.frames["chatContents"]) //IE5, Konq, Safari
cWindow = window.frames["chatContents"];
else if(chatContents.contentWindow) //IE5.5+, Moz 1.0+, Opera
cWindow = chatContents.contentWindow;
else //Moz < 0.9 (Netscape 6.0)
cWindow = chatContents;
//set up a reference to the document object of the IFRAME
if(cWindow.document) //Moz 0.9+, Konq, Safari, IE, Opera
cDocument = cWindow.document;
else //Moz < 0.9 (Netscape 6.0)
cDocument = cWindow.contentDocument;
}
function insertMessages(content){
//place the new messages in a div
var newDiv = cDocument.createElement("DIV");
newDiv.innerHTML = content;
//append the messages to the contents
cDocument.getElementById("contents").appendChild(newDiv);
//scroll the chatContents area to the bottom
cWindow.scrollTo(0,cDocument.getElementById("contents").offsetHeight);
}
function resetForm(){
document.getElementById("message").value = "";
document.getElementById("message").focus();
}//-->
</script>
</head>
<body>
<h1>jenChat</h1>
<a href="login.php?logout=true">Logout</a><br />
<iframe id="chatContents" name="chatContents" src="contents.html"></iframe>
<form target="post" method="post" action="post.php">
<input type="text" name="message" id="message" style="width: 250px" />
<input type="submit" value="Send" class="submit" />
</form>
<iframe id="post" name="post" src="post.php"
style="width: 0px; height: 0px; border: 0px;"></iframe>
<iframe id="thread" name="thread" src="thread.php"
style="width: 0px; height: 0px; border: 0px;"></iframe>
</body>
</html>
That will collect the information and write it out.
next, post.php
CODE
<?php
require_once('init.php');
/* make sure the person is logged in. */
if(!isset($_SESSION['jenChat_UserID']))
exit;
/* make sure something was actually posted. */
if(sizeof($_POST)){
$expiretime = date("YmdHis",time() - 5);
/* delete expired messages. */
mysql_query("DELETE FROM jenChat_Messages
WHERE Posted <= '" . $expiretime . "'");
/* delete inactive participants. */
mysql_query("DELETE FROM jenChat_Users
WHERE LastUpdate <= '" . $expiretime. "'");
/* post the message. */
mysql_query("INSERT INTO jenChat_Messages (UserID,Posted,Message)
VALUES(
" . $_SESSION['jenChat_UserID'] . ",
'" . date("YmdHis", time()) . "',
'" . mysql_real_escape_string(strip_tags($_POST['message'])) . "'
)");
header("Location: post.php");
exit;
}
?>
<!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" lang="en-US" xml:lang="en-US">
<head>
<script type="text/javascript"><!--
if(parent.resetForm)
parent.resetForm();
//-->
</script>
</head>
</html>
Next and last,
thread.php
CODE
<?php
require_once('init.php');
/* make sure the person is logged in. */
if(!isset($_SESSION['jenChat_UserID']))
exit;
$currtime = date("YmdHis",time());
/* maintains this user's state as active. */
mysql_query("UPDATE jenChat_Users SET LastUpdate = '" . $currtime . "'
WHERE UserID = " . $_SESSION['jenChat_UserID']);
/* grab any messages posted since the last time we checked.
Notice we say >= and <. This is to guarantee that we don't miss any
messages that are posted at the same instant this query is
executed.*/
$sql = "SELECT Message,UserName
FROM jenChat_Messages
INNER JOIN " . "jenChat_Users
ON jenChat_Messages.UserID = jenChat_Users.UserID
WHERE Posted >= '" . $_SESSION['jenChat_Prevtime'] . "'
AND Posted < '" . $currtime . "'
ORDER BY Posted";
$res = mysql_query($sql);
?>
<!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" lang="en-US" xml:lang="en-US">
<head></head>
<body>
<?
if(mysql_num_rows($res)){
echo '<div id="contents">';
while($row = mysql_fetch_array($res)){
echo '<div><strong>' .
htmlspecialchars($row['UserName']) . ': </strong>' .
htmlspecialchars($row['Message']) . '</div>';
}
echo '</div>';
}
$_SESSION['jenChat_Prevtime'] = $currtime;
?>
<script type="text/javascript"><!--
if(parent.insertMessages && document.getElementById("contents"))
parent.insertMessages(document.getElementById("contents").innerHTML);
setTimeout("getMessages()", 1000); //poll server again in one second
function getMessages(){
document.location.reload();
}
//-->
</script>
</body>
</html>
well, that is the chat script!!
If u want to profide a css file, that would be great!!