Jump to content
xisto Community
Sign in to follow this  
friiks

Simple Shoutbox PHP, MySQL driven..

Recommended Posts

Ok, so I'm going to show you how to create a very basic shoutbox which is driven with PHP and a MySQL database.

 

So, lets start - open a database management program like PHPMyAdmin and run these queries.

CREATE TABLE `shoutbox` (
`id` INT( 11 ) NOT NULL AUTO_INCREMENT ,
`name` VARCHAR( 255 ) NOT NULL ,
`mail` VARCHAR( 255 ) NOT NULL ,
`time` VARCHAR( 255 ) NOT NULL ,
`message` TEXT NOT NULL ,
`ip` VARCHAR( 255 ) NOT NULL ,
PRIMARY KEY ( `id` )
) TYPE = MYISAM ;

CREATE TABLE `shoutbox_admin` (
`id` INT( 11 ) NOT NULL AUTO_INCREMENT ,
`name` VARCHAR( 255 ) NOT NULL ,
`password` VARCHAR( 255 ) NOT NULL ,
PRIMARY KEY ( `id` )
) TYPE = MYISAM ;

INSERT INTO `shoutbox_admin` (`id`,`name`,`password`) VALUES ('NULL', 'your_username', 'your_md5_hashed_password')

replace your_username with your username [for administration]

and your_md5_hashed_password with a password that has been md5 hashed. You can google for md5 hasher or just create a php file which contains this

<?php$mypass='your_password';$mypass=md5($mypass);echo $mypass;?>

Congratulations, your database is ready to be used :P

 

Next we will create a form.

Make a file called form.htm or any name you want it to be called.

Put this code in it.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<title>Shoutbox</title>
</head>
<body>
<iframe src='shouts.php' width='150px' height='250px'></iframe>
<form method="post" action="doit.php">
<input type='text' name='name' value='Name' onfocus='this.value=""'><br>
<input type='text' name='mail' value='E-mail' onfocus='this.value=""'><br>
<textarea name='message' onfocus='this.value=""' rows='3' cols='15'>Your text</textarea><br>
<input type='submit' value='submit' name='submit'>
</form>
</body>
</html>

Here we create a form which will send data to a file that will insert the data into the database :D

And I'm using an iframe to view the shoutbox as I couldn't find a code to refresh only one <div>.

 

Ok, now for the file that will read the data sent from our form and will insert it into database.

Create a file called doit.php and put this code in it.

<?php//including the database connectioninclude('config.php');//getting everything that has been submitted$name=mysql_real_escape_string(strip_tags($_POST['name']));$mail=mysql_real_escape_string(strip_tags($_POST['mail']));$message=mysql_real_escape_string(strip_tags($_POST['message']));$submit=$_POST['submit'];//get the current time with php date() function//note that the server time will be recorded//more info about all functions - http://php.net$time=date("m/d/y");//get the ip. Note that this wont see through proxies$ip=$_SERVER['REMOTE_ADDR'];//just some basic error checking which//checks if name,e-mail and message //hasnt been left blank or with default textif (($name!=="") || ($name!=="Name") || ($mail!=="") || ($mail!=="E-mail") || ($message!=="") || ($message!=="Your text")){//inserts data into the database$sql = "INSERT INTO shoutbox (id, name, mail, message, time, ip) VALUES ('NULL', '$name', '$mail', '$message', '$time', '$ip')";mysql_query($sql) or die(mysql_error());//sends the user back to the formheader("Location:".$_SERVER['HTTP_REFERER']);}else{header("Location:".$_SERVER['HTTP_REFERER']);}?>

Ah, config.php, forgot about it!

Create a file named like that and put this in it.

<?php	$dbhost   = 'database host';	$dbname   = 'database name';	$dbusername   = 'database username';	$dbuserpass = 'database password';		mysql_connect ($dbhost, $dbusername, $dbuserpass);mysql_select_db($dbname) or die('Cannot select database');?>
I guess you understand which parts you have to edit here.

 

Ok, now for the final part - file that will output the shouts.

Create a file named shouts.php and this is the code to put in it.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><style type="text/css"><!--.shout{padding-bottom:4px;border-bottom:1px solid #000;width:150px;text-align:left;font-family:verdana;font-size:10px;}--></style><title>Shoutbox</title></head><body onLoad=window.setTimeout("location.href='shouts.php'",10000)><?phpinclude('config.php');$result = mysql_query("select * from shoutbox order by id desc limit 5");//the while loopwhile($r=mysql_fetch_array($result)){	     //getting each variable from the table   $time=$r["time"];   $id=$r["id"];   $message=$r["message"];   $name=$r["name"];	 $mail=$r['mail'];echo "<div class='shout'>	Shouted on: <i>".$time."</i><br>	By <b><a href='mailto:".$mail."'>".$name."</b></a><br>	".$message."<br>   </div><br>";} ?></body></html>
The final code just gets all data from database and is outputted with a while loop. note that you can add pagination, limit...anything to this. This is a very simple shoutbox example.

 

If you have any questions please ask as I may have forgotten something...

 

I will add the administration later as my headache is killing me. Here's my files if someone wants to see.

shoutbox.zip

 

Edit:

Oh yea, wanted to include the preview :$

clickie^^

 

Edit No.2:

 

The Administration Panel!


$idg=$_GET['id'];

?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

 

<html>

<head>

<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">

<title>ACP</title>

</head>

<body>

<?php

//include config.php

include 'config.php';

//get the username from the form and add some security

//so you cant get hacked so easy linenums:0'><?php //Start the session so you would stay logged in..//must be ABOVE ANY outputsession_start(); //Get the cmd variable$cmd=$_GET['cmd'];$idg=$_GET['id'];?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1"><title>ACP</title></head><body><?php//include config.phpinclude 'config.php';//get the username from the form and add some security//so you cant get hacked so easy :P$username = mysql_real_escape_string(strip_tags(htmlspecialchars($_POST['username'])));$password = md5($_POST['password']);//if login button is pressedif ($_POST['login']){//check if username and password are insertedif((!$username) || (!$password)){//if not tell them to...do insert all of infoecho "Please enter both values<br>";}//when they have we check if the username and the password exists$sql = mysql_query("SELECT * FROM `shoutbox_admin` WHERE `name` = '$username' AND `password`= '$password'") OR die(mysql_error());//so we need to check it for real //mysql_num_rows() counts the rows which are returned as true$login_check = mysql_num_rows($sql);//if the check is true....true = 1 and $login check is set as $login_check=1if($login_check > 0){//so if it is larger than 1 we set some session variables -//username and id$r=mysql_fetch_array($sql);$_SESSION['id'] = $r['id'];$_SESSION['username'] = $r['name'];//if it's not let's make him suffer...moahahahaa...//reload the page I mean.. :P}else {header("Refresh:2;admin.php");echo 'Go and login <-<';}}//so if session username isn't set show user the login formif(!isset($_SESSION['username'])){?><center><form action='<?=$_SERVER['PHP_SELF']?>' method='POST'>Username: <input type='text' size='15' name='username'><br>Password: <input type='password' size='15' name='password'><br><input name="login" type="submit" value="Submit"></form></center><? }//if not - show him the contents and stuff...else{//welcome message and logout link...echo "<center>Welcome, ". $_SESSION['username'] ."! <a href='logout.php'>Log Out</a></center>";echo "<br><br><center>";//see my ?id= browsing tutorial to understand switch()switch($cmd){default://getting all of the shouts and adding `delete me` link...$result = mysql_query("select * from shoutbox order by id desc"); while($r=mysql_fetch_array($result)) { $name=$r["name"];$message=$r["message"];$time=$r["time"];$id=$r["id"];echo "Shout by: ".$name." <strong>@</strong> ".$time."<br>".$message."<br><a href='?cmd=delete&id=".$id."'>Delete me</a><br><br>";}break;case 'delete':$sql = "DELETE FROM shoutbox WHERE id=".$idg."";$result = mysql_query($sql);header('Refresh:2;admin.php');echo "deleted";};} ?>


logout.php

<?session_start();$_SESSION = array();header("Location: index.php");?>

admin.php - admin.php

logout.php - logout.php

Edited by friiks (see edit history)

Share this post


Link to post
Share on other sites

friiks,

Looks like a nice script, but any chance that you could include a live demo link for people to check out?

And for those who are Database challenged, check out this link.

Share this post


Link to post
Share on other sites

Looks good to me! Im glad you made this so i can see how i can modify mine. The problem i have with working with DB's is not the coding itself but the planning of the coding, i start it then realise i need another table or DB and eventually it messes up and i give up!

I also like the fact that not the entire page needs to be refreshed, by using the IFRAMES you can have only that frame refreshing to update the shouts. Im not much of a fan of frames though so i guess either of us could use an include or something which is what i generally use nowadays and then use the data from a variable to echo out to the page, by doing this it might be possible to update just the data inside a DIV, either way i used a textarea because its simpler :D

I also like the fact you included some NULL data checking

if (($name!=="") || ($name!=="Name") || ($mail!=="") || ($mail!=="E-mail") || ($message!=="") || ($message!=="Your text"))

I think thats a good idea to help with spamming issues, if you wanted to get even more in depth you could also record IP's and ban them from shouting for several seconds to stop flooding but now im just being picky!

Good work there :P

Share this post


Link to post
Share on other sites

awesome, I've been looking for a simple shoutbox I could host myself. Thank you very much for this tutorials. There is one suggestion I would make though, a little more explination of the code would help for those who are unfamiliar with the code and would like to learn what each line does. Either way, thanks a ton for the tutorial.

Share this post


Link to post
Share on other sites

Thank you for the replies :PAnd @ t3jem, I knew I commented the code too less, I was just in little hurry when submitting this so I'll add some more comments when I update the topic with a file for the administration.

Share this post


Link to post
Share on other sites

Well, you have to change the color/theme, anything yourself. This is a tutorial in which I give you the code to learn from. You can get css and colorize it.. :P

Share this post


Link to post
Share on other sites

That is a really good tutorial on making a simple shout box but is there flood control and is there a way to clear all the shouts that it has stored up in the database or set a time for it to clean out the shouts? Also is there a way to ban or replace bad words from your shout box?

Share this post


Link to post
Share on other sites

The title is right, very simple and limited in features. Though may I suggest adding something to the tutorial? Make a PHP file that runs the SQL as in $sql = "SQL TABLE DATA HERE"; so it can create the tables by just editing database in one file (giving the info) and opening the file. It will help people who are database challanged.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.