PHP Development Board php divider

User Options
Register--Login--Top 20 Posters--Search Topics


Forum Main>>Tutorials>>Simple chatbox tutorial

New Topic-Reply




Author
Post
Chipmunk

Rank:Settler of Bobland
Group: Head Administrator
Posts: 2867
IP Logged

PM ID and RPS ID: 1
PM [Chipmunk]

View Member Photo

Last replied to on Wed Dec 21, 2011 05:03:58
Edit Post|Quote
Ok, this is going to be a tutorial that will show you how to build the frontend of a PHP/MYSQL based chatbox that has a WYSIWYG built in.


First we need to set up the mySQL database:
We're going to call this table chatmessages for this tutorial. It needs 5 fields:

ID - Bigint, primary , auto increment
name - varchar 255
IP - varchar 255
postime - bigint
message - I'd say tinytext, but you can do medium text if you want your users to be able to post over 400 chars per post.

The second table is for a list of all ipbans:
IPID - Auto generated IP, primary Auto increment, bigint
IP - varchar 255 - this is where we wil store the actual IP


So you need 3 files for the main chatbox.

1 file we'll call chatbox.php as the main file to hold the other two frames.

Another file called chatlog.php that will Display the messages and a third file called send.php we'll use to send the messages.

The later 2 files will be iframes in the first file.
We also need a connect.php file for mySQL database connection:

connect.php
Code:

<?php
$db = mysql_connect("localhost", "username", "password") or die("Could not connect."); //username and password
if(!$db)
die("no db");
if(!mysql_select_db("database_name",$db)) //database name
die("No database selected.");

if(!get_magic_quotes_gpc())
{
$_GET = array_map('mysql_real_escape_string', $_GET);
$_POST = array_map('mysql_real_escape_string', $_POST);
$_COOKIE = array_map('mysql_real_escape_string', $_COOKIE);
}
else
{
$_GET = array_map('stripslashes', $_GET);
$_POST = array_map('stripslashes', $_POST);
$_COOKIE = array_map('stripslashes', $_COOKIE);
$_GET = array_map('mysql_real_escape_string', $_GET);
$_POST = array_map('mysql_real_escape_string', $_POST);
$_COOKIE = array_map('mysql_real_escape_string', $_COOKIE);
}


?>


First we will work on submit.php

Code:

<?php
include "connect.php";
if(isset($_POST['submit'])) //if submit button push has been detected
{
$message=$_POST['message'];
$name=$_POST['name'];
if(strlen($message)<1)
{
print "You did not input a message";
}
else if(strlen($name)<1)
{
print "You did not enter a name, please try again.";
}
else
{
$message=strip_tags($message);
$IP=$_SERVER["REMOTE_ADDR"]; //grabs poster's IP
$checkforbanned="SELECT IP from ipbans where IP='$IP'";
$checkforbanned2=mysql_query($checkforbanned) or die("Could not check for banned IPS");
if(mysql_num_rows($checkforbanned2)>0) //IP is in the banned list
{
print "You IP is banned from posting.";
}
else
{
$thedate = date("U"); //grab date and time of the post
$insertmessage="INSERT into chatmessages (name,IP,postime,message) values('$name','$IP','$thedate','$message')";
mysql_query($insertmessage) or die("Could not insert message");


}
}


}
print "<form action='submit.php' method='post' name='form'>";
print "Your name:<br>";
print "<input type='text' name='name' size='20'><br>";
print "Your message:<br>";
print "<textarea name='message' cols='40' rows='2'></textarea><br>";
print "<a onClick=\"addSmiley(':)')\"><img src='images/smile.gif'></a> "; //replace images/smile.gif with the relative path of your smiley
print "<a onClick=\"addSmiley(':(')\"><img src='images/sad.gif'></a> ";
print "<a onClick=\"addSmiley(';)')\"><img src='images/wink.gif'></a> ";
print "<input type='submit' name='submit' value='submit'></form>";
print "<script language=\"Java Script\" type=\"text/javascript\">\n";
print "function addSmiley(textToAdd)\n";
print "{\n";
print "document.form.message.value += textToAdd;";
print "document.form.message.focus();\n";
print "}\n";
print "</script>\n";
print "<br><br>";

?>



This is the file that will submit a user's message into th database. At the bottom you see the form that asks for your poster's name and
the message he wants to post. The onclick and following javascript function allows for clickable smilies. If you want more, simple add more smilies in and copy and paste more:
Code:

print "<a onClick=\"addSmiley(':(')\"><img src='images/sad.gif'></a> ";


lines in, change the :( into the character you want for your smiley and the image path to the image path of your smiley.
The code that comes in the:
Code:

if(isset($_POST['submit'])) //if submit button push has been detected
{


case is basically validation code for message, it checks to make sure the poster's name and message is at least 1 character long and if it isn't, it doesn't post and gives an error message telling them that one of the required fields is not valid. Next it gets the poster's posting IP with the $_SERVER["REMOTE_ADDR"] function and checks that IP against the table of banned IP with $checkforbanned. If the IP is found in the list of banned IPS, it throws an error message saying that your IP is banned and does not post the message. Finally, if all the conditions are met, it grabs the current unix timestamp wth $date("U") and posts all the information into the message database.

Now lets look at chatlog.php, the file that displays the messages, the newest messages will be posted at the bottom:

Code:

<?php
include "connect.php";
$getnummessages="SELECT COUNT(*) as messagecount from chatmessages";
$getnummessages2=mysql_query($getnummessages) or die("blah");
$getnummessages3= mysql_result($getnummessages2, 0);
if($getnummessages3>21)
{
$startrow=$getmessages3-20;
}
else
{
$startrow=1;
}
$getmsg="SELECT name, message from chatmessages order by postime ASC limit $startrow,$getnummessages3";
$getmsg2=mysql_query($getmsg) or die(mysql_error());
while($getmsg3=mysql_fetch_array($getmsg2))
{
$message=Smiley($message); //Smiley faces
print "<font color='red'><b>$getmsg3[name]:</b></font> $getmsg3[message]<br>";

}

function Smiley($texttoreplace)
{
$smilies=array(


':)' => "<img src='images/smile.gif'>",
':blush' =>"<img src='images/blush.gif'>",
':angry' =>"<img src='images/angry.gif'>",
':o'=> "<img src='images/shocked.gif'>",
'fuck'=>"$#$%",
'Fuck'=>"&$#@"


);

$texttoreplace=str_replace(array_keys($smilies), array_values($smilies), $texttoreplace);
return $texttoreplace;
}
?>
<script>
setTimeout("window.location.replace('chatlog.php')",2000);

</script>


Basically , this first counts the number of messages there are in the database first, then subtracts 20 from that number and stored that value in $startrow.
Then we grab all the messages from $startrow to the last message in the database and look through the array to display the 20 messages, with the latest message at the bottom. The smilies function replaces the smiley characters with the actual smiley images, not that this can also be used as a bad words
filter. The last line simply refreshes the page automatically every 2 seconds, so that new messags will automatically come up, just like a real chatroom.

Now we can look at chatframe.php which is a simple page with two iframes to hold the submit page and the chatlog page.

chatframe.php

Code:

<?
print "<iframe src='chatlog.php' name='chatlogframe' width='350' height='400'></iframe>";
print "<br><br>";
print "<iframe src='submit.php' width='350' height='150' frameborder='0'></iframe><br><br>";
?>




There's really nothing to this file, just two iframes to hold the other two files.

The next post will be the admin files.

-----------------------------
Chipmunk,
Supreme Administrator

Chipmunk

Rank:Settler of Bobland
Group: Head Administrator
Posts: 2867
IP Logged
PM ID and RPS ID: 1
[PM Chipmunk]

View Member Photo

Posted at Sun Mar 18, 2007 16:12:55
Edit post|Quote
The next part of this tutorial will be building some basic admin things for the chatroom. All these files will go in a /admin folder which will be password
protected. I am assuming you have a control panel(such as cpanel or directadmin) that offer password protection for directories.

If you don't please take a look at
http://www.javascriptkit.com/howto/htaccess3.shtml


Basically, this simple admin panel will consist of three primary functions, banning IPs, editing messages, and deleting messages. So put this link bar at the top of very page of this admin panel:

Code:

<A href='banip.php'>Ban IPS</a> | <A href='unbanip.php'>Unban IP</a> | <A href='editdelete.php'>Edit/Delete messages</a><br>


First we will look at banip.php, its quite simple:

Code:


<?php
include "../connect.php";
if(isset($_POST['submit']))
{
$banip=$_POST['banip'];
if(strlen($banip)<1)
{
print "You did not list an IP to Ban";
}
else
{
$ipban="Insert into ipbans (IP) values('$banip')";
mysql_query($ipban) or die("Could not ban IP");
print "Ip banned.";
}

}
else
{
print "<form action='banip.php' method='post'>";
print "IP to Ban:<br>";
print "<input type='text' name='banip' size='20'><br>";
print "<input type='submit' name='submit' value='submit'></form>";
}
?>


Basically this is just a form and when you hit submit it checks to see if anything was entered, and if something was, it inserts it into the banned IPS database.

Now lets look at unbanip.php:

Code:

<?php
include "../connect.php";
if(isset($_POST['submit']))
{
$ipselects=$_POST['ipselects'];
$unban="Delete from ipbans where ipid='$ipselects'";
mysql_query($unban) or die("Could not unban");
print "IP Unbanned.";

}
else
{
print "<form action='unbanip.php' method='post'>";
$getips="SELECT * from ipbans";
$getips2=mysql_query($getips) or die("Could not get IPS");
print "<select name='ipselects'>";
while($getips3=mysql_fetch_array($getips2))
{
print "<option value='$getips3[ipid]'>$getips3[IP]</option>";
}
print "</select><br>";
print "<input type='submit' name='submit' value='submit'></form>";
}
?>


This basically prints a form, queries the database to get all the banned ips and uses the while loops on the query results to print them all out
as options in a select element of the form. When you hit submit, it deletes the IP from the banned IP list based on the ID of the IP stored in the database.

Now lets look at the code for editing and deleting messages:

editdelete.php
Code:

<?php
include "../connect.php";
if(isset($_POST['submit']))
{
$searchterm=$_POST['searchterm'];
$getmsg="Select * from chatmessages where message like '%$searchterm%' order by postime desc";
$getmsg2=mysql_query($getmsg) or die("Could not get messages");
print "<table border='1'><tr><td>Name of poster</td><td>IP</td><td>Message</td><td>Edit</td><td>Delete</td></tr>";
while($getmsg3=mysql_fetch_array($getmsg2))
{
print "<tr><td valign='top'>$getmsg3[name]</td><td valign='top'>$getmsg3[IP]</td><td valign='top'>$getmsg3[message]</td><td valign='top'><A href='editm.php?ID=$getmsg3[ID]'>Edit</a></td><td valign='top'><A href='delete.php?ID=$getmsg3[ID]'>Delete</a></td></tr>";
}
print "</table>";

}
else
{
print "<form action='editdelete.php' method='post'>";
print "Search for messages(leaving blank will return all messages:<br>";
print "<input type='text' name='searchterm' size='20'><br>";
print "<input type='submit' name='submit' value='submit'></form>";

}
?>


This print out a simple form asking you for a search term that appears in the message you are searching for. Since we are matching on like, if you leave it blank,
all messages will be returned in last-to-first order.
After you hit submit, it queries for the message containing the terms you search for and print them neately in a table so you can edit or delete.

Now we require 2 more files to finish this admin panel, editm.php and delete.php, lets take a look at those.

editm.php

Code:

<?php
include "../connect.php";
if(isset($_POST['submit']))
{
$ID=$_POST['ID'];
$themessage=$_POST['themessage'];
$updatemsg="Update chatmessages set message='$themessage' where ID='$ID'";
mysql_query($updatemsg) or die("Could not get message");
print "Message updated.";

}
else
{
$ID=$_GET['ID'];
$getmessage="SELECT * from chatmessages where ID='$ID'";
$getmessage2=mysql_query($getmessage) or die("Could not get message");
$getmessage3=mysql_fetch_array($getmessage2);
print "<form action='editm.php' method='post'>";
print "<input type='hidden' name='ID' value='$ID'>";
print "<textarea name='themessage' rows='5' cols='50'>$getmessage3[message]</textarea><br><br>";
print "<input type='submit' name='submit' value='submit'></form>";


}
?>


So Basically in this file, when you click on the edit link, it draws out the contents of the page based on the ID defined in the URL. Then it prints a form with the message in the textfield you can edit. When you click submit it passed the ID of the message and the edited message and then uses a mysql update query to update the message.

So at last lets look at delete.php

Code:

<?php
include "../connect.php";
if(isset($_POST['submit']))
{
$ID=$_POST['ID'];
$delmessage="Delete from chatmessages where ID='$ID'";
mysql_query($delmessage) or die("Could not delete message");
print "Message Deleted.";

}
else
{
$ID=$_GET['ID'];
print "<form action='delete.php' method='post'>";
print "Are you sure you want to delete this message?<br>";
print "<input type='hidden' name='ID' value='$ID'>";
print "<input type='submit' name='submit' value='Delete'></form>";
}
?>


This code get the ID from the ID specified in the URL, stores it in a hidden field and confirms that you want to delete the message. Once you
hit the delete button, it passed the ID and then deletes the message from the mySQL database based on that ID.

Thats it, a simple chatbox with admin panel.
-----------------------------
Chipmunk,
Supreme Administrator

Page: 1



Powered by Chipmunk Board

Flash games Ninja games-Web Design New York