Implementing a Comments System

Embedded malicious scripts, editable comments without login, etc.

Page 1 of 1

10 Replies - 1045 Views - Last Post: 18 June 2008 - 11:46 AM Rate Topic: -----

#1 atdrago  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 27
  • Joined: 08-June 08

Implementing a Comments System

Posted 17 June 2008 - 11:06 PM

Hello all,

I'm making a comments system for my site and I'm seeking some advice. One thing to keep in mind: I do not require any account creation to make a comment.

First, I don't want the users to be able to use HTML, or any kind of scripting language for obvious reasons. But I would like to allow the users to be able to post their own code. Would using regular expressions to replace all '<' with '&lt;' keep any actual scripts or HTML from being added to the site?

I'd also like the user to be able to edit his or her own comment after it has been posted. Would creating a cookie effectively achieve this? Keep in mind I don't want to require an account creation to comment.

Last, is there anything else I need to worry about?

Thanks for any advice! :)

Adam

Is This A Good Question/Topic? 0
  • +

Replies To: Implementing a Comments System

#2 akozlik  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 89
  • View blog
  • Posts: 797
  • Joined: 25-February 08

Re: Implementing a Comments System

Posted 17 June 2008 - 11:43 PM

Use regex to strip out any html that's being posted. If you're looking to allow for code, it might be easier to allow users to use pastebin for displaying code. Just google pastebin for more information.

Remember that regular expression is used for finding patterns in text. You need to make sure you set it up to strip anything between < and > characters.

As far as cookies, it really depends. If you're not implementing a login system, a cookie may be fine. You could set the cookie to allow for a user to edit their post within 10 days of it being posted, but that has obvious limitations.

You really might want to implement a login system. It would make your life a lot easier, and make it easier to have more control over your site.
Was This Post Helpful? 0
  • +
  • -

#3 atdrago  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 27
  • Joined: 08-June 08

Re: Implementing a Comments System

Posted 17 June 2008 - 11:55 PM

Well I don't want to strip the stuff between the < and >, I want it all to be displayed, just not compiled (if that makes sense). Would replacing '<' with '&lt;' and '>' with '&gt;' not achieve this?

And I agree with you that a user login would be handy if somebody wanted to post multiple comments and have his or her own profile on the site. But for just wanting to respond to an article or blog post, I think filling out a sign up form and logging in is extremely tedious and may turn away some potential users.
Was This Post Helpful? 0
  • +
  • -

#4 akozlik  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 89
  • View blog
  • Posts: 797
  • Joined: 25-February 08

Re: Implementing a Comments System

Posted 18 June 2008 - 12:03 AM

View Postatdrago, on 18 Jun, 2008 - 02:55 AM, said:

Well I don't want to strip the stuff between the < and >, I want it all to be displayed, just not compiled (if that makes sense). Would replacing '<' with '&lt;' and '>' with '&gt;' not achieve this?

And I agree with you that a user login would be handy if somebody wanted to post multiple comments and have his or her own profile on the site. But for just wanting to respond to an article or blog post, I think filling out a sign up form and logging in is extremely tedious and may turn away some potential users.


As long as the comments will be displayed as html you should be find. Just use str_replace() to search for the < and > characters.

The problem you're going to have is determining which posts belong to which user, without having any sort of user authentication. There really aren't very many ways you can do that without a user system. What's keeping you from having people sign up? As long as you make it a quick process I doubt you'd lose that many readers. Most people who care enough to leave a comment will sign up anyway. Think about adding a user system.
Was This Post Helpful? 0
  • +
  • -

#5 Ändrew  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 25
  • View blog
  • Posts: 312
  • Joined: 21-April 08

Re: Implementing a Comments System

Posted 18 June 2008 - 02:38 AM

Hi I made this tutorial for you while i was eating cupcakes and making a clan website.

Ok its simple only if you have a MySQL or SQL or what ever kind of database.
The one im going to show is MySQL and PHP implemented together.
First lets make our data base. Using this query.
CREATE TABLE comment(
id INT NOT NULL AUTO_INCREMENT,
title VARCHAR(50) NOT NULL,
content TEXT NOT NULL,
PRIMARY KEY(id)
);

Now this will make a table named comment with ID,title,and the content.
Ok we must make a way to comment so make a new .php called commentadd.php.
Put this code in it.
<?php
if(isset($_POST['save']))
{
   $title   = $_POST['title'];
   $content = $_POST['content'];

   if(!get_magic_quotes_gpc())
   {
      $title   = addslashes($title);
      $content = addslashes($content);
   }
   include 'config.php';
   include 'opendb.php';

   $query = " INSERT INTO comment (title, content) ".
            " VALUES ('$title', '$content')";
   mysql_query($query) or die('Error ,query failed');

   include 'closedb.php';

   echo "Comment '$title' added";
}
?>
<form method="post">
<table width="700" border="0" cellpadding="2" cellspacing="1" align="center">
<tr>
<td width="100">Title</td>
<td><input name="title" type="text"></td>
</tr>
<tr>
<td width="100">Content</td>
<td><textarea name="content" cols="50" rows="10"></textarea></td>
</tr>
<tr>
<td width="100"> </td>
<td> </td>
</tr>
<tr>
<td colspan="2" align="center"><input name="save" type="submit" value="Save Article"></td>
</tr>
</table>
</form>

Now as you see above you can see /config.php and others we must make them!
To make them from these instructions.
1. Create a new .php file named config.php and put this code in it. (Depending on the database username and password)
<?php
$dbhost = 'localhost';
$dbuser = 'example';
$dbpass = 'omgapassword';
$dbname = 'examplename';
?>

2. Create a new .php file named opendb.php and put this code in it.
<?php
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);
?>

3.Create a new .php file named closedb.php and put this code in it.
<?php
mysql_close($conn);
?>

AND THATS IT! You can now post comments but we have a problem! We want to retrive them!
Depending on how to want to set it out try both ways. Experiment with the code a bit!
Create a new .php file named commentnolinks.php and put this code in it.
This is one that will show the comments with out links to them!
<DIV align="left" Comments: </DIV>
<?php
include 'config.php';
include 'opendb.php';

$query  = "SELECT id, title, content FROM comment ORDER BY id";
$result = mysql_query($query);

while($row = mysql_fetch_assoc($result))
{
    echo "<h2>{$row['title']}</h2> <br><br><br>" .
         "{$row['content']} <br><br>";
}

include 'closedb.php';
?>

This will show the Comments.
Create a new .php file named commentlinks.php and put this code in it.
This will have links of the comments in a order from 1-infinity.
<?php
include 'config.php';
include 'opendb.php';

if(!isset($_GET['id']))
{
   $self = $_SERVER['PHP_SELF'];

   $query = "SELECT id, title FROM comment ORDER BY id";
   $result = mysql_query($query) or die('Error : ' . mysql_error());

   $content = '<ol>';
   while($row = mysql_fetch_array($result, MYSQL_NUM))
   {
      list($id, $title) = $row;
      $content .= "<li><a href=\"$self?id=$id\">$title</a></li>\r\n";
   }

   $content .= '</ol>';

   $title = 'Comments';
} else {
   $query = "SELECT title, content FROM comment WHERE id=".$_GET['id'];
   $result = mysql_query($query) or die('Error : ' . mysql_error());
   $row = mysql_fetch_array($result, MYSQL_ASSOC);

   $title = $row['title'];
   $content = $row['content'];
}

include 'closedb.php';
?>

Thats really all to it. Now to implement them into your pages just use the code.
//your web artical here or picture or hack or what ever it is
include 'commentnolink.php'; //you can use links if you want
include 'commentadd.php';


Now I also saw you want to edit them as well Lucky i have that too!
1. Create a new .php file named commentadmin.php and put this code in it.
<?php
include 'config.php';
include 'opendb.php';

if(isset($_GET['del']))
{
   $query = "DELETE FROM news WHERE id = '{$_GET['del']}'";
   mysql_query($query) or die('Error : ' . mysql_error());

   $cacheDir = dirname(__FILE__) . '/cache/';
   $cacheFile = $cacheDir . '_' . $_GET['id'] . '.html';

   @unlink($cacheFile);

   @unlink($cacheDir . 'index.html');

   header('Location: ' . $_SERVER['PHP_SELF']);
   exit;
}
<html>
<head>
<title>Comment Admin Page</title>
<script language="Javascript">
function delComment(id, title)
{
   if (confirm("Are you sure you want to delete '" + title + "'"))
   {
      window.location.href = 'commentadmin.php?del=' + id;
   }
}
</script>
</head>

<body>
<?php
$query = "SELECT id, title FROM comment ORDER BY id";
$result = mysql_query($query) or die('Error : ' . mysql_error());
?>
<table width="600" border="0" align="center" cellpadding="5" cellspacing="1" bgcolor="#999999">
<tr align="center" bgcolor="#CCCCCC">
<td width="500"><strong>Title</strong></td>
<td width="150"><strong>Action</strong></td>
</tr>
<?php
while(list($id, $title) = mysql_fetch_array($result, MYSQL_NUM))
{

?>
<tr bgcolor="#FFFFFF">
<td width="500">
<?php echo $title;?>
</td>
<td width="150" align="center">
<a href="commentlinks.php?id=<?php echo $id;?>" target="_blank">view</a>
 <a href="commentedit.php?id=<?php echo $id;?>">edit</a>
 <a href="java script:delComment('<?php echo $id;?>',
 <?php echo $title;?>');">delete</a></td>
</tr>
<?php
}

include 'closedb.php';
?>
</table>
</body>
</html>

You can change any thing in there to suite your needs.
2.Create a new .php file named commentedit.php and put this code in it.
<html>
<head>
<title>Edit A Comment</title>
</head>

<body>
<?php
include 'config.php';
include 'opendb.php';

if(isset($_GET['id']))
{
   $query  = "SELECT id, title, content ".
             "FROM comment ".
             "WHERE id = '{$_GET['id']}'";
   $result = mysql_query($query) or die('Error : ' . mysql_error());
   list($id, $title, $content) = mysql_fetch_array($result, MYSQL_NUM);

   $content = htmlspecialchars($content); // Ok this is where if you want to get rid of people using HTML!
}
else if(isset($_POST['save']))
{
   $id = $_POST['id'];
   $title = $_POST['title'];
   $content = $_POST['content'];

   if(!get_magic_quotes_gpc())
   {
      $title = addslashes($title);
      $content = addslashes($content);
   }

   $query = "UPDATE comment ".
            "SET title = '$title', content = '$content' ".
            "WHERE id = '$id'";
   mysql_query($query) or die('Error : ' . mysql_error());

   $cacheDir = dirname(__FILE__) . '/cache/';
   $cacheFile = $cacheDir . '_' . $_GET['id'] . '.html';

   @unlink($cacheFile);

   @unlink($cacheDir . 'index.html');

   echo "Comment '$title' updated";

   $title   = stripslashes($title);
   $content = stripslashes($content);
}

include 'closedb.php';
?>
<form method="post">
<input type="hidden" name="id" value="<?=$id;?>">
<table width="700" border="0" cellpadding="2" cellspacing="1" class="box">
<tr>
<td width="100">Title</td>
<td><input name="title" type="text" class="box" id="title" value="<?=$title;?>"></td>
</tr>
<tr>
<td width="100">Content</td>
<td><textarea name="content" cols="50" rows="10" class="box" id="content"><?=$content;?></textarea></td>
</tr>
<tr>
<td width="100"> </td>
<td> </td>
</tr>
<tr>
<td colspan="2" align="center"><input name="update" type="submit" class="box" id="update" value="Update Comment"></td>
</tr>
</table>
<p align="center"><a href="commentadmin.php">Back to admin page</a></p>
</form>
</body>
</html>

If you followed this All correct you have also made your very first News System!
You can also add Heaps like Name, email, and many many more using this template.

Ändrew

PS: if you need username and password thing for admin i can tell you.
Was This Post Helpful? 0
  • +
  • -

#6 atdrago  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 27
  • Joined: 08-June 08

Re: Implementing a Comments System

Posted 18 June 2008 - 05:39 AM

wow, Andrew.

Thank you very much but I prefer not to use other people's work. (And I know most of that stuff already) But submit it as a tutorial and maybe you'll get some dream kudos or something. :)

akozlik,

I'm not really sure why I'd need to determine which posts belong to which user. Unless the user would want to see his or her history, but then again that wouldn't be offered and I'm not really trying to get that deep with it. I agree with you that making a user system could eliminate lots of the trouble I'll have (spamming, cursing, etc.) because it gives each user their own 'identity' and could potentially prevent that, but I believe there are many people who would appreciate a quick, simple comment area with just two simple fields. That said, I'll probably end up making a user system sometime in the future (lol).

I already have the comment system working on my test server, I just need to implement that str_replace() jive and do some other error checking.

One more question though. It looks like I'll have to enclose the user's comment in <pre></pre> tags so that they could do their own indenting and line ends and stuff. The only problem I'm experiencing with doing that is that if the user doesn't end the line, it will continue past the length of the division or paragraph. Is there some way to prevent this (inserting a '\n' after every so many characters on each line) or is there some other way to set the number of characters allowed in a division?

Thanks again. :)
Was This Post Helpful? 0
  • +
  • -

#7 AdaHacker  Icon User is offline

  • Resident Curmudgeon

Reputation: 452
  • View blog
  • Posts: 811
  • Joined: 17-June 08

Re: Implementing a Comments System

Posted 18 June 2008 - 07:23 AM

View Postatdrago, on 18 Jun, 2008 - 05:39 AM, said:

I just need to implement that str_replace() jive and do some other error checking.

You know, you could have just used htmlspecialchars() instead of mucking with str_replace(). It converts all angle brackets, quotes, and ampersands to their equivalent HTML entities. It effectively blocks HTML from being rendered, but keeps your pages valid.

Quote

The only problem I'm experiencing with doing that is that if the user doesn't end the line, it will continue past the length of the division or paragraph.

If you don't want to wrap the text, the easiest way to keep it from messing up your page is to use the overflow style. This will control what happens when the text is larger than the content of its container. For example, this will add a horizantal scroll bar if the text is wider than the 100 pixel DIV:
<div style="width: 100px; white-space: pre; overflow: auto">
This is some really long line of text which, for whatever reason, we really don't want to break.
</div>

Was This Post Helpful? 1
  • +
  • -

#8 akozlik  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 89
  • View blog
  • Posts: 797
  • Joined: 25-February 08

Re: Implementing a Comments System

Posted 18 June 2008 - 09:38 AM

You need a user system because you have no way to identify which comments belong to who. You want them to be able to edit which comments are theirs, but how do you plan on knowing which comments are theirs? The best way I can think of is to write a basic authentication system, and only allow the user to edit comments that belong to them. That's why it's important to have a user system.
Was This Post Helpful? 1
  • +
  • -

#9 joeyadms  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 41
  • View blog
  • Posts: 178
  • Joined: 04-May 08

Re: Implementing a Comments System

Posted 18 June 2008 - 11:26 AM

Editing comments.. Heres what I would do.

- Run ALL output through htmlspecialchars()
- Make code blocks in bb style and put everything inbetween in an overflow and in between <pre></pre>
- Once a comment is posted give the user a few minutes to edit the post by using a fingerprint of their ip/browser, storing this info in Session variables.

Another option is giving that user a pin number to edit posts, and tell them to use it again when posting new comments, not a very good option, but its something to get your mind turning.

Simple.. Secure.. Me likes

Oh and don't forget ANY kind of variable, no matter through which medium it comes from, use mysql_real_escape_string() or your DBMS equivelant.
Was This Post Helpful? 1
  • +
  • -

#10 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1638
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Re: Implementing a Comments System

Posted 18 June 2008 - 11:37 AM

This is just my opinion, but I wouldn't even worry about requiring users to register before posting and editing comments. I cant think of a single site out there that allows users to post and edit comments w/o requiring them to register first. You could make it something as simple as getting their name and email, that way an ID can be assigned to them. Just my 2 cents :)
Was This Post Helpful? 1
  • +
  • -

#11 atdrago  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 27
  • Joined: 08-June 08

Re: Implementing a Comments System

Posted 18 June 2008 - 11:46 AM

Thanks a lot, everyone. Thank you's have been distributed accordingly. ;)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1