Quantumstate
05-20-2008, 09:27 AM
Making a simple message board so that people can add their own comments to your web page is actually a very simple script.
First we should make a database connection file. I prefer to keep this separate. This allows you to put it in a separate folder if you wish for security and I also use a similar file in every small script I make.
<?php
$dbusername = "username";
$dbpassword = "password";
$database="dbname";
$sqllink=mysql_connect('localhost',$dbusername,$db password);
@mysql_select_db($database);
?>
This is fairly basic stuff. Just stick in the right values and then we can include the file. This will establish a connection with the database so we can then run any queries we like. I called mine dbinfo.php.
Next the table needs to be created. Mine has 4 fields; id, title, email, message. I also called it message (I probably shouldn't have the same name but it still works). Here is the mysql query:
CREATE TABLE `messages` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`title` TEXT NOT NULL ,
`email` TEXT NOT NULL ,
`message` TEXT NOT NULL
)
Next we need to code the form which the user uses to submit their comment. This consists of title and email input boxes and a textarea for their message.
<h2>Post Comment</h2>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
Title: <input type="text" name="title"><br/>
Email: <input type="text" name="email"> (not displayed)<br/>
Message:<br/>
<textarea name="message">
</textarea>
<input type="submit" value="Submit Comment"/>
</form>
I have given it a title. The forms action is pointing to itself since we will use the same page for all of our scripting. The other stuff is pretty basic html. The names are important so that we can read in the values. And of course there is a submit button. You can save this into any file you want. I called mine message_board.php. It must be a php file.
Now we get onto the scripting for the submission script. First we open the php tags and include our database file. This code should go at the top of the page above the form.
<?php
include('dbinfo.php');
Next is the input check. First the message and title are checked to see if they actually have something written in them. If the title is not compulsory then remove the if statement. After this we use a regex (regular expression) match to test whether it is a valid email address. I found the regular expression to test for an email address here.
if ($_POST['message'] != '' ){
if ($_POST['title'] != ''){
if (preg_match('^[a-zA-Z]([.]?([[:alnum:]_-]+)*)?@([[:alnum:]\-_]+\.)+[a-zA-Z]{2,4}$^', $_POST['email'])){
}else{
echo "Invalid email address";
}
}else{
echo "Please enter a title";
}
}else{
echo "You must enter a message";
}
Below are the else statements to give error messages if it went wrong.
Now, if everything was correct then the input needs to be correctly formatted. The first step is making the stuff safer. This means stopping mysql injection and also stripping out html tags. Once this is done an attacker cannot cause any harm. There are php functions which do these things for you which is nice.
$message = strip_tags($_POST['message']);
$title = strip_tags(mysql_real_escape_string($_POST['title']));
$email = mysql_real_escape_string($_POST['email']);
You may have noticed with this code that mysql_real_escape string is not applied to the message. This is done later on in the process for a reason which will become clear. Also I have stored the post values in handy variables which are easier to access.
The next part is sorting out the message part. We do some more advanced formatting to this. The main thing is to replace the new line characters with <br/> tags since we know that new lines don't show up if placed in html code. I have also added an example of some BBcode. More complex BBcode can be added by the same method.
$find = array("\r\n", "\n", "\r", "", "");
$replace = array('<br />', '<br />', '<br />', '<b>', '</b>');
$message = str_replace($find, $replace, $message);
Each value in the first array is replaced by it's corresponding value in the second array. There are three different new line characters depending on operating system. Smilies can also be added with this method by using with <img src="smile.jpg"/>.
Now we can make the message safe for mysql. If we had done this beforehand then the new lines would not have been replaced because the mysql_real_escape_string changes these characters.
$message = mysql_real_escape_string($message);
Finally we can put the data into our table with a very simple INSERT query.
$query = "INSERT INTO `messages` (`id`, `title`, `email`, `message`) VALUES (NULL, '$title', '$email', '$message')";
$result = mysql_query($query);
echo "Thankyou for posting your message.<br/><br/>";
The id column is auto incrementing so we need not specify a number. Also we output a nice friendly message saying it was a success.
Next we move on to outputting the messages that have been submitted. First we run a query to select all of the messages. This code can go directly underneath the submission code. The submission code should go first because then the new submission will appear straight away rather than needing a page refresh.
$query = "SELECT * FROM `messages`";
$result = mysql_query($query);
Now we have everything from the table in $result, we will loop through it all.
while ($message = mysql_fetch_array($result)){
echo "<b>{$message['title']}</b><br/>";
echo $message['message'] . "<br/><br/>";
}
This fetches an array for each row of the results. The output formatting that I have used is very basic, just making the title bold and adding new lines between things. You might want to make the formatting much nicer. The email address should probably be kept private since most people will not want it shown publicly due to spam and privacy. Come to think of it I am not actually sure why I added it in the first place. I guess if you wanted to contact someone after they gave a useful comment. It could easily be removed.
To edit or delete comment you must use a database management tool such as phpMyAdmin.
That is all of the script. Here are the contents of the whole file for those who wish to just copy and paste it.
<?php
include('dbinfo.php');
if ($_POST['message'] != '' ){
if ($_POST['title'] != ''){
if (preg_match('^[a-zA-Z]([.]?([[:alnum:]_-]+)*)?@([[:alnum:]\-_]+\.)+[a-zA-Z]{2,4}$^', $_POST['email'])){
$message = strip_tags($_POST['message']);
$title = strip_tags(mysql_real_escape_string($_POST['title']));
$email = mysql_real_escape_string($_POST['email']);
$find = array("\r\n", "\n", "\r", "", "");
$replace = array('<br />', '<br />', '<br />', '<b>', '</b>');
$message = str_replace($find, $replace, $message);
$message = mysql_real_escape_string($message);
$query = "INSERT INTO `messages` (`id`, `title`, `email`, `message`) VALUES (NULL, '$title', '$email', '$message')";
$result = mysql_query($query);
echo "Thank you for posting your message.<br/><br/>";
}else{
echo "Invalid email address";
}
}else{
echo "Please enter a title";
}
}else{
echo "You must enter a message";
}
$query = "SELECT * FROM `messages`";
$result = mysql_query($query);
while ($message = mysql_fetch_array($result)){
echo "<b>{$message['title']}</b><br/>";
echo $message['message'] . "<br/><br/>";
}
?>
<h2>Post Comment</h2>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
Title: <input type="text" name="title"><br/>
Email: <input type="text" name="email"> (not displayed)<br/>
Message:<br/>
<textarea name="message">
</textarea>
<input type="submit" value="Submit Comment"/>
</form>
Suggestions for improvements you could add
1. Make it possible to keep comments from multiple pages in one table (Hint: add a field to store the $SERVER['PHP_SELF'] value)
2. Add more advanced BBcode support with preg_replace (There is a fairly serious flaw with my BBcode, can you spot it?)
I am quite sure, that the error in your script, is that:
Say a user wants to write:
Welcome to the COMMENTS
But they leave off the [/b], your str_replace would still replaced the with <b> but would not close of the bold styling.
Therefore, the rest of the page would become on big page of bold text
This is easily fixed using preg_replace was you said:
$text = "Welcome to the [b]COMMENTS";
$text = preg_replace("/\[b\](.*?)\[\/b\]/is", "<b>$1</b>", $str);
That is the little bug yes ?
3. Add a spam control part to the script (Hint: use a regular expression to search for things such as website addresses)
First we should make a database connection file. I prefer to keep this separate. This allows you to put it in a separate folder if you wish for security and I also use a similar file in every small script I make.
<?php
$dbusername = "username";
$dbpassword = "password";
$database="dbname";
$sqllink=mysql_connect('localhost',$dbusername,$db password);
@mysql_select_db($database);
?>
This is fairly basic stuff. Just stick in the right values and then we can include the file. This will establish a connection with the database so we can then run any queries we like. I called mine dbinfo.php.
Next the table needs to be created. Mine has 4 fields; id, title, email, message. I also called it message (I probably shouldn't have the same name but it still works). Here is the mysql query:
CREATE TABLE `messages` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`title` TEXT NOT NULL ,
`email` TEXT NOT NULL ,
`message` TEXT NOT NULL
)
Next we need to code the form which the user uses to submit their comment. This consists of title and email input boxes and a textarea for their message.
<h2>Post Comment</h2>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
Title: <input type="text" name="title"><br/>
Email: <input type="text" name="email"> (not displayed)<br/>
Message:<br/>
<textarea name="message">
</textarea>
<input type="submit" value="Submit Comment"/>
</form>
I have given it a title. The forms action is pointing to itself since we will use the same page for all of our scripting. The other stuff is pretty basic html. The names are important so that we can read in the values. And of course there is a submit button. You can save this into any file you want. I called mine message_board.php. It must be a php file.
Now we get onto the scripting for the submission script. First we open the php tags and include our database file. This code should go at the top of the page above the form.
<?php
include('dbinfo.php');
Next is the input check. First the message and title are checked to see if they actually have something written in them. If the title is not compulsory then remove the if statement. After this we use a regex (regular expression) match to test whether it is a valid email address. I found the regular expression to test for an email address here.
if ($_POST['message'] != '' ){
if ($_POST['title'] != ''){
if (preg_match('^[a-zA-Z]([.]?([[:alnum:]_-]+)*)?@([[:alnum:]\-_]+\.)+[a-zA-Z]{2,4}$^', $_POST['email'])){
}else{
echo "Invalid email address";
}
}else{
echo "Please enter a title";
}
}else{
echo "You must enter a message";
}
Below are the else statements to give error messages if it went wrong.
Now, if everything was correct then the input needs to be correctly formatted. The first step is making the stuff safer. This means stopping mysql injection and also stripping out html tags. Once this is done an attacker cannot cause any harm. There are php functions which do these things for you which is nice.
$message = strip_tags($_POST['message']);
$title = strip_tags(mysql_real_escape_string($_POST['title']));
$email = mysql_real_escape_string($_POST['email']);
You may have noticed with this code that mysql_real_escape string is not applied to the message. This is done later on in the process for a reason which will become clear. Also I have stored the post values in handy variables which are easier to access.
The next part is sorting out the message part. We do some more advanced formatting to this. The main thing is to replace the new line characters with <br/> tags since we know that new lines don't show up if placed in html code. I have also added an example of some BBcode. More complex BBcode can be added by the same method.
$find = array("\r\n", "\n", "\r", "", "");
$replace = array('<br />', '<br />', '<br />', '<b>', '</b>');
$message = str_replace($find, $replace, $message);
Each value in the first array is replaced by it's corresponding value in the second array. There are three different new line characters depending on operating system. Smilies can also be added with this method by using with <img src="smile.jpg"/>.
Now we can make the message safe for mysql. If we had done this beforehand then the new lines would not have been replaced because the mysql_real_escape_string changes these characters.
$message = mysql_real_escape_string($message);
Finally we can put the data into our table with a very simple INSERT query.
$query = "INSERT INTO `messages` (`id`, `title`, `email`, `message`) VALUES (NULL, '$title', '$email', '$message')";
$result = mysql_query($query);
echo "Thankyou for posting your message.<br/><br/>";
The id column is auto incrementing so we need not specify a number. Also we output a nice friendly message saying it was a success.
Next we move on to outputting the messages that have been submitted. First we run a query to select all of the messages. This code can go directly underneath the submission code. The submission code should go first because then the new submission will appear straight away rather than needing a page refresh.
$query = "SELECT * FROM `messages`";
$result = mysql_query($query);
Now we have everything from the table in $result, we will loop through it all.
while ($message = mysql_fetch_array($result)){
echo "<b>{$message['title']}</b><br/>";
echo $message['message'] . "<br/><br/>";
}
This fetches an array for each row of the results. The output formatting that I have used is very basic, just making the title bold and adding new lines between things. You might want to make the formatting much nicer. The email address should probably be kept private since most people will not want it shown publicly due to spam and privacy. Come to think of it I am not actually sure why I added it in the first place. I guess if you wanted to contact someone after they gave a useful comment. It could easily be removed.
To edit or delete comment you must use a database management tool such as phpMyAdmin.
That is all of the script. Here are the contents of the whole file for those who wish to just copy and paste it.
<?php
include('dbinfo.php');
if ($_POST['message'] != '' ){
if ($_POST['title'] != ''){
if (preg_match('^[a-zA-Z]([.]?([[:alnum:]_-]+)*)?@([[:alnum:]\-_]+\.)+[a-zA-Z]{2,4}$^', $_POST['email'])){
$message = strip_tags($_POST['message']);
$title = strip_tags(mysql_real_escape_string($_POST['title']));
$email = mysql_real_escape_string($_POST['email']);
$find = array("\r\n", "\n", "\r", "", "");
$replace = array('<br />', '<br />', '<br />', '<b>', '</b>');
$message = str_replace($find, $replace, $message);
$message = mysql_real_escape_string($message);
$query = "INSERT INTO `messages` (`id`, `title`, `email`, `message`) VALUES (NULL, '$title', '$email', '$message')";
$result = mysql_query($query);
echo "Thank you for posting your message.<br/><br/>";
}else{
echo "Invalid email address";
}
}else{
echo "Please enter a title";
}
}else{
echo "You must enter a message";
}
$query = "SELECT * FROM `messages`";
$result = mysql_query($query);
while ($message = mysql_fetch_array($result)){
echo "<b>{$message['title']}</b><br/>";
echo $message['message'] . "<br/><br/>";
}
?>
<h2>Post Comment</h2>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
Title: <input type="text" name="title"><br/>
Email: <input type="text" name="email"> (not displayed)<br/>
Message:<br/>
<textarea name="message">
</textarea>
<input type="submit" value="Submit Comment"/>
</form>
Suggestions for improvements you could add
1. Make it possible to keep comments from multiple pages in one table (Hint: add a field to store the $SERVER['PHP_SELF'] value)
2. Add more advanced BBcode support with preg_replace (There is a fairly serious flaw with my BBcode, can you spot it?)
I am quite sure, that the error in your script, is that:
Say a user wants to write:
Welcome to the COMMENTS
But they leave off the [/b], your str_replace would still replaced the with <b> but would not close of the bold styling.
Therefore, the rest of the page would become on big page of bold text
This is easily fixed using preg_replace was you said:
$text = "Welcome to the [b]COMMENTS";
$text = preg_replace("/\[b\](.*?)\[\/b\]/is", "<b>$1</b>", $str);
That is the little bug yes ?
3. Add a spam control part to the script (Hint: use a regular expression to search for things such as website addresses)