Welcome Guest ( Log In | Register )



 
Reply to this topicStart new topic
> LiveThunder's Shoutbox


 
satish
post Jan 8 2008, 03:11 AM
Post #1


Admin
Group Icon
Group: Root Admin
Posts: 980
Joined: 8-October 06
From: In my server...
Member No.: 1





Now that you know the basics of PHP and MySQL connectivity, its time to add a little interaction with this cool little applet that allows your users to leave short messages - a system commonly referred to as a shoutbox. In this tutorial I will detail everything you need to know about making your very own shoutbox, right down from the HTML form, to the smilies emotion configuration and anti-spam measures.

You will need the following to be able to complete this tutorial:

* * A PHP enabled webserver.
* * A mySQL database.
* * An hour of free time.
* * Sessions enabled.
* * File uploads enabled.

Getting Started
As a first step we should think about the layout and size of our shoutbox - 150px wide and 500px high is just about right. I'll refrain from using an iframe in my example because I really don't like them. We'll also give the shoutbox a 10 entry display limit (i.e. the latest 10 entries will display - the rest will be hidden). With these considerations aside, we can start by setting up two mySQL tables in our database: shouts and smilies.

shouts has 4 fields:
- id, int(11), auto_increment, PRIMARY
- Name, TEXT
- Shout, TEXT

- Contact, TEXT

smilies has 4 fields:
- id, int(11, auto_increment, PRIMARY
- Symbol, VARCHAR(4)
- URL, TEXT
- Alt, TEXT

If you don't know what this formatting means, int is the type of field, the number in brackets is the size, auto_increment is a feature, and PRIMARY is a type, defining it as unique. Text is a field type, as is VARCHAR, and the number in brackets again is the field length.

With these tables in place you should create your shoutbox directory, and then a subdirectory off it called smilies. CHMOD it to 777 (i.e. all permissions).

Breakdown of shout.php
CODE
// calling session_start() the function which starts our authentication session
session_start();
// connecting to mysql server
$l = mysql_connect ( "localhost" , "user" , "pass" ) or die("Error connecting:<BR><BR>".mysql_error());
mysql_select_db( "user" ) or die("Error getting db:<BR><BR>".mysql_error());

This is the main building block of both scripts. It starts all session registering or management with session_start(), and then selects and connects to our database. You should, of course, edit the mySQL connectivity lines to reflect your own mySQL settings.
CODE
function getShouts()
{

echo '<div align="center">
<table width="150" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>
';

$query = mysql_query("SELECT * FROM shouts ORDER BY id DESC LIMIT 10") or die(mysql_error());
while ($row = mysql_fetch_array($query) )
{

$name = stripslashes($row['Name']);
$contact = stripslashes($row['Contact']);
$shout = stripslashes($row['Shout']);

if(empty($contact))
{

echo '<p><span class="author">'.$name.'</span> - <span class="shout">'.$shout.'</span></p>';

} else {

echo '<p><span class="author"><a href="'.$contact.'" target="_blank">'.$name.'</a></span> - <span class="shout">'.$shout.'</span></p>';

} // if empty contact

} // while row mysqlfetcharray query

echo '<br><br>';

echo '
</td>
</tr>
<tr>
<td height="10"> </td>
<form name="shout" method="post" action="shout.php">
<div align="center">
<input name="name" type="text" id="name" value="Name" size="25" maxlength="10"><br>
<input name="contact" type="text" id="contact" value="http://" size="25"><br>
<input name="message" type="text" id="message" value="Message" size="25"><br>
<input name="shout" type="submit" id="shout" value="Shout!">
</div>
</form>
</td>
</tr>
</table>
</div>
';

} // function getshouts

This is probably the most important function for the whole script, as it processes and displays the shouts. First of all, this function selects the newest 10 shouts by ordering them by id in descending order. It then cycles through and displays the records. The author and message tags have SPAN classes around them, but I haven’t defined the applicable CSS tags. If you wish to define them, go to line 87 of shout.php where it says /* STARTING THE MAIN SCRIPT NOW */, and add the following code below it:

echo ‘<link href="yourfile.css" rel="stylesheet" type="text/css">’;

In yourfile.css add two classes: author and shout, which are self explanatory as to where they will appear. This will be very useful when you want to format your shouts cohesively.

Now, back to our function. In addition to what I said earlier, it removes the slashes from our database results (because we added some when we posted them), and it checks to see whether or not the contact variable was empty when the user posted. If the user did not specify any contact information, a plain name is displayed without a hyperlink. If the opposite happens, their name is enclosed within a nice big hyperlink instead.
CODE
if ( isset ( $_POST['shout'] ) )
{

$name = addslashes($_POST['name']);
$contact = addslashes($_POST['contact']);
$message = $_POST['message'];

if ( ( isset($name) ) && ( isset($message) ) )
{

// getting smilie list
$smilies = mysql_query("SELECT * FROM smilies") or die(mysql_error());
while($get = mysql_fetch_array ($smilies))
{

$alt = $get['Alt'];
$smilie = $get['URL'];

$message = str_replace( $get['Symbol'] , '<img src="smilies/'.$smilie.'" border="0" width="15" height="15" alt="'.$alt.'">' , $message);
$themessage = addslashes($message);

// replacing all smilies

}

mysql_query("INSERT INTO shouts (Name, Contact, Shout) VALUES ( '$name' , '$contact' , '$message' )") or die(mysql_error());
$_SESSION['has_posted'] = 'yes';
header("Location: shout.php");

// if required fields aren't empty, process into database

} else {

echo '<script>alert("Some fields were not filled out!");</script>';
header("Location: shout.php");

// if required fields were left empty, show an error dialog

}

}

This is a rather large function, but there's no need to panic as its pretty simple in operation, and shows off a couple of anti-spam functions too. As you can probably guess, this function processes the shout submissions and puts them into the database, after replacing smilie symbols with user-defined and uploaded images (see admin.php). Before it does this, though, it checks that the user actually came from the form, which is a useful anti-spam feature and stops some degree of remote hijacking. After this, it checks that all the data fields have been filled in properly on the form and displays a nice big error message if the user doesn't fill out their name or a shout. With all of the checking out of the way, our function then gets all the smilies out of the database, replaces the applicable ones in the shout message, and finally adds slashes before passing it on to be processed. The shout is then processed and added to the database.

As a final anti-spam measure, the script sets a session to indicate that the user has already posted a message. To post a second message the user would have then to restart their browser.

That’s the shout.php file out of the way! Now we can move onto the admin.php file that allows us to add/delete the shouts, add new smilies, etc.

Breakdown of admin.php
We can skip the “building block” because it’s the same as the one at the start of shout.php. The first block of code in our admin.php file defines the login credentials, i.e. the username and password. Pretty simple really:
CODE
$username = "adminuser";
$password = "password";

CODE
Next in line is the login checking function:
[code]if ( isset ( $_POST['login'] ) )
{

if (( $_POST['username'] === $username ) && ( $_POST['password'] === $password ))
{

$_SESSION['admin_logged_in'] = 'true';

}

}

CODE
This function checks that the login button has been pressed, and the user came from the right place (i.e. OUR script). It then checks that the username and password are correct before setting the session so that the user can see the admin cp.

function selectAction ( $mode )
{

switch ($mode)
{

case '':
echo 'Welcome to the administration panel, make the selection above.';
break;

case 'add':
echo '
<form action="admin.php?mode=posting" method="post" name="addSmilie" enctype="multipart/form-data">
<input name="symbol" type="text" value="=)" size="25" maxlength="4"><br>
<input name="image" type="file"><br>
<input name="addsmilie" type="submit" value="Add Smilie!"><br><br>
Check your symbol and filename, I couldnt be bothered writing an "edit smilie" function. Please note, as this is not a gdlib tutorial, there are no file dimensions protections. Please only upload 15x15 pixel smilies, if they are not this size, they will be skewed when they are resized when displayed.
</form>
';
break;

case 'delete':
$query = mysql_query("SELECT * FROM smilies") or die(mysql_error());
while($row = mysql_fetch_array($query)){

echo '<a href="admin.php?mode=posting&smilie='.$row['id'].'">
<img src="smilies/'.$row['URL'].'" border="0" width="15" height="15" alt="'.$row['Alt'].'">
</a><br><br>
';

}
break;

case 'clear':
mysql_query("TRUNCATE TABLE shouts") or die(mysql_error());
echo 'Shoutbox cleared successfully!';
break;

case 'logout':
$_SESSION['admin_logged_in'] = '';

header("Location: admin.php");
break;

case 'posting':
if(isset($_POST['addsmilie'])){

$uploaddir = 'smilies/';

$uploadfile = $uploaddir . $_FILES['image']['name'];

//echo '<br><br>'.$uploaddir.'<br>'.$uploadfile.'<br><br>';

$upload = move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile);
echo '<pre>';
if( $upload == TRUE ) {

echo 'Success';

} else {

echo 'Error';
print_r($_FILES);
exit;

}
print "</pre>";

$alt = $_FILES['image']['name'];
$symbol = $_POST['symbol'];
$url = $_FILES['image']['name'];

mysql_query("INSERT INTO smilies(Symbol, URL, Alt) VALUES('$symbol','$url','$alt')") or die(mysql_error());
echo '<br><br>Successfully inserted smilie!<br><br><a href="admin.php">Admin</a> | <a href="shout.php">Shouts</a>';
exit;

}

if(isset($_GET['smilie'])){

$smilie = $_GET['smilie'];
mysql_query("DELETE FROM smilies WHERE id = '$smilie' LIMIT 1") or die(mysql_error());
echo 'Successfully deleted smilie!<br><br><a href="admin.php">Admin</a> | <a href="shout.php">Shouts</a>';

}
break;

default:

} // end switch
} // end if


[/code]
A simple switch function has 4 or 5 cases, each of which are similar to using an IF statement. To put it simply, our switch checks which option the user has chosen (i.e. add smilie, delete smilie, clear shoutbox, logout, nothing or posting) and then processes the correct code. The add smilie and delete smilie options are the only two that need further processing - the clear shoutbox and logout cases just handle themselves in a line or two.

The add smilie case provides the user with a basic form to input the original symbol i.e. =) or =O, and then a box to upload a replacement smilie image. There are no dimension protections in our script, but we should limit ourselves to images 15x15 pixels in size, or they will look silly when displayed in the shoutbox text. Transparent GIF’s are a good option, as they allow a whole multitude of different background colours.

The delete smilie case provides the user with a list all of the current smilies and, when the user clicks one, the posting case authenticates the click and deletes the appropriate smilie.

The posting case is based on the add smilie case. It first authenticates that the user wants to upload a smilie, then defines the directory to upload to, and uploads the file. It then puts the filename into the ALT and URL fields in the database with the Symbol equal to the symbol field on the form.

Emptying the shoutbox uses the SQL query: TRUNCATE TABLE [tablename] to completely empty the table, removing all shouts in the database in milliseconds.
CODE
if ( $_SESSION['admin_logged_in'] === 'true' )
{

Well… this just makes sure the user is logged in with administrator permissions before continuing. Now we can finally get out of functions and into the actual HTML of the page:
CODE
<html>
<head>
<title>Shoutbox Administration</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<p>Smilie administration: <a href="admin.php?mode=add">add smilie</a> | <a href="admin.php?mode=delete">delete smilie</a></p>
<p>Shoutbox administration: <a href="admin.php?mode=clear">clear shoutbox</a> | <a href="admin.php?mode=logout">logout</a></p>
<table width="600" border="1" cellpadding="5" bordercolor="#ccc">
<tr>
<td><?php selectAction($_GET['mode']); ?></td>
</tr>
</table>
</body>
</html>

This is just basic HTML with a title, some links and a content area that calls the selectAction function, providing it with the URL variable ‘mode’. This page probably won't validate through a HTML standards checker, but it is only meant as an example anyway.
CODE
<?php

// showing login form
} else {

echo '
<form action="admin.php" method="post" name="login">
<input name="username" type="text" value="username" size="25" maxlength="32"><br>
<input name="password" type="password" value="password" size="25" maxlength="32"><br>
<input name="login" type="submit" value="login">
</form>
';

}

mysql_close($l);
?>


This final snippet of code ensures that if the user isn’t logged in, he/she will be given a nice login form to inwardly digest instead...


--------------------
Go to the top of the page
 
+Quote Post

 
cheating98
post Jan 9 2008, 09:39 PM
Post #2


Junior Member
Group Icon
Group: Members
Posts: 32
Joined: 9-January 08
Member No.: 6,391





Do you have a demo?
Go to the top of the page
 
+Quote Post


Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 

RSS Lo-Fi Version Time is now: 7th January 2009 - 07:04 PM
IPB skin developed by: eXtremepixels