Create a homemade comment management on your site

My kids wanted to be able to comment on our family site - no big deal I thought, there have to be hundreds of examples on the web and - Google is your friend - started to search. I found nothing suitable and had to tinker something for myself. When you want to use it or to build on it download the zip file with the js and php scripts. For the expand and collapse feature you'll need tho copy also the 2 images in the Image folder included in the zip to your domain.

Basic Concept

Step by Step

ToDo's on your page

Include the JavaScript in the head of pages where you want to place a comment section. At my site it looks like this:


<script type="text/javascript" src="../js/collapse_expand_single_item.js"></script>
Putting a comment somewhere in your site you just call the function like this

<?php	comment('richard38', false); ?>

The richard38 represents both the html tag (for getting back to this section) and the comment ID which identifies the comments in the database. Naturally your comment IDs need to be unique.
For SQLITE to work you need to activate SQLITE support in you PHP (It's a long time ago ... you'll have to google it. There is plenty of help out there).
When you have set up a SQLITE DB (When you name it differently you'll have to change "comments.sqlite" in the scripts to your name), set up the tables. When you copy my example putting this in the SQL window of your DB GUI (I use the wonderfull Firefox addon SQLit Manager) should do the job:


CREATE TABLE com_list (DateTime TEXT, Username TEXT, link TEXT);
CREATE TABLE comments (com_id TEXT, Username TEXT, comment TEXT, DateTime TEXT, link TEXT, linkdescription TEXT);
CREATE TABLE "spamuser" ("pk_spamuser_id" INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL  UNIQUE , "spamuser" TEXT);
For the comments to work you need to reference the comment.php script the head section of your page:


<?php
// include comments
include($_SERVER['DOCUMENT_ROOT'].'/php/comment.php');

?>
And here is the php script comment.php with the function:

<?php
// /php/comment.php

function comment($comid, $commentoff = false) {


  	// set path of database file
	$file = "sqlite:".$_SERVER['DOCUMENT_ROOT']."/comtxt/comments.sqlite";
	$db = new PDO($file) or die("Could not open database");

	// open database file and query comments with given ID
	$query = "SELECT  * FROM 'comments' WHERE com_id = '".$comid
		."' ORDER BY rowid DESC";


	// execute query
	$result = $db->query($query) or die("Error in query ".$db->lastErrorMsg());

	// Retrieve number of comments for a given ID
	$query = "SELECT  count(1) FROM 'comments' WHERE com_id = '".$comid	."'";

	$count = $db->query($query) or die("Error in query ".$db->lastErrorMsg());

	foreach($count as $fields) {
	 $com_count = $fields[0]	;
	}

  // compose header string
  print '<br /><br /><a name="_' . $comid . '"></a>';
  print "There are ". $com_count . " comments <br />";

 	$comstr = '<p><img src="/Images/expand.gif" name="img';
 	$comstr .= $comid;
 	$comstr .= '"><a href="#_';
 	$comstr .= $comid;
	$comstr .= '" onclick="shoh';
	$comstr .= "('";
	$comstr .= $comid;
	$comstr .= "')";
	$comstr .= ";";
	$comstr .= '">Read comments and write your own</a></p>';
	$comstr .= '<div style="display: none; margin-left: 3em;" id="';
 	$comstr .= $comid;
 	$comstr .= '" >';
  // print header string
 	print $comstr;

	  // Loop through comment records an pring
 	   foreach($result as $fields) {
 	 		$comment_text =  "<b>" . $fields[1] . "</b>". " wrote ". $fields[3] ."<br />" .
			"<p>".$fields[2]."<br />";
//			when link is filled then add the fields to the com_lines
		  	if ($fields[4] != ''){
  			$comment_text = $comment_text .  "<a href='".$fields[4].
				"' target='_blank' rel='nofollow'> Link ". $fields[5]. "</a></p>";
		  	}  // if Link
           print $comment_text;
                print "<br />";
           }
	unset($db);

	// if new comment enabled ($commentoff = false) diplay the comment form
	if ($commentoff == false) {
?>

	<form action="/php/com_handling.php" method="post">

 		 <br />Your input is wanted! Put in a name: <br />
		 <input type="hidden" name="ID" value=<?php echo $comid ?>>
		 <input type="hidden" name="request_url" value=<?php echo $_SERVER["REQUEST_URI"] ?>>
		 <input name ="username" size=40>
 		 <br /> ... and a comment (should be at least 10 characters):<br />
		 <textarea name ="commenttext" cols="90"  rows="5"></textarea>
		 <br /> To share a link put in the url:
		 <input name="url" size=55>
		 <br /> ...and here a link description:
		 <input name="linkdescription" size=55>
		 <br />  skip this field (spam-trap!), just push submit
		 <input name="checktext" size=20>
		 <input type="submit" name="submit"  value="Send"> ...and you are done!

	</form>

	</div>

<?php

  }   // if commentoff
  else {
    echo "<b>Closed for new comments</b>";
    echo "</div>";
  }

}   // function comment

?>
And now we need the script com_handling.php which is processing the readers comment and stores it into the DB

<?php
// /php/com_handling.php

// functions used in the script
function check_input($data) {
// cleans the input data

    $data = stripslashes($data);
    $data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8');
 	$data = str_replace("\n", "<br />",$data); //replace newlines with <br />
 	$data = str_replace("\r", "",$data);		  // remove hard returns
 	$data = str_replace("#", "",$data);		  // remove # as this is the separator in the comment file
	$data = sqlite_escape_string($data);
 //	$data = utf8_encode($data);



    return $data;
} // function check input

function f_AddQuotes($textstring, $quote) {

	$quotedstring = $quote .$textstring .$quote;

	return $quotedstring;


}

// Start of script
		// set path of database file
		$file = "sqlite:".$_SERVER['DOCUMENT_ROOT']."/comtxt/comments.sqlite";
		$db = new PDO($file) or die("Could not open database");

		// Get data from comment form
		$request_url =  $_POST['request_url'];
 		$id = $_POST['ID'];
 		$commenttext = check_input($_POST['commenttext']);
		$url = check_input($_POST['url']);
		$linkdescription = check_input($_POST['linkdescription']);
		$comurl = $request_url ."#_".$id;
		$checktext = $_POST['checktext'];
		$mydate = getdate();
		$datestring = $mydate['weekday'] .' '.$mydate['month'] . ' '.$mydate['mday'] . ' '.   $mydate['year']. '@'.$mydate['hours']. ':'.str_pad($mydate['minutes'],2,"0");

	// check if username is in the spamuser table
	$username = check_input($_POST['username']);
	$query = "SELECT * FROM spamuser WHERE spamuser LIKE '%".substr($username,0,5)."%'";

// get array spam user
	$stmt = $db->Query($query) or die("Error in query ".$db->lastErrorMsg());
	$result = $stmt->fetchAll();

   // When not empty then the user is in the spamlist
   if (empty($result)) {

		// Check whether all fields match your conditions (mostly spam protection)
 		if (strlen($checktext) == 0 && strrpos($id, "+") == false
 			&& strrpos($commenttext, "://") == false
 			&& strlen($commenttext) > 9 && strlen($username) > 0)
 			{

  		// write into table com_list in comment.sqlite
 		$query = "INSERT INTO com_list (DateTime, Username, link) " .
 				"VALUES(" .
 				f_AddQuotes($datestring,"'") ."," .
 				f_AddQuotes($username,"'") ."," .
 				f_AddQuotes($comurl,"'") .
  				")";
		$result = $db->query($query) or die("Error in query ");

		// write into table comments in comment.sqlite
  		$query = "INSERT INTO comments (com_id, Username, comment, DateTime, link," .
 				" linkdescription) VALUES(" .
 				f_AddQuotes($id,"'") ."," .
 				f_AddQuotes($username,"'") ."," .
 				f_AddQuotes($commenttext,'"') ."," .
 				f_AddQuotes($datestring,"'") ."," .
  				f_AddQuotes($url,"'") ."," .
  				f_AddQuotes($linkdescription,"'") .
  				")";

 		$result = $db->query($query) or die("Error in query ");

 		}	// if checktext
 		else {  // write comment details into a text file - just to see how much spam your prevented
  		// write to spam_list.txt
 		$spamfile = $_SERVER['DOCUMENT_ROOT'].'/comtxt/spam_list.txt';
		$fh = fopen($spamfile, 'a') or die('Could not open file!');
		fwrite($fh, $id.$username.$datestring."\n" ) or die('Could not write to file');
		fclose($fh);

 		}
 	}
		// close DB and go back to the page
		unset($db);
		header("Location: ".$comurl);

?>

Simple Comment Tracker

With the following little script you can print your recent comments (you can adjust the number; here the Limit is set to 8. It shows date, time, commenters name and a hyperlink to the commented page.


<?php
// /php/com_list.php

	// set path of database file
	$file = "sqlite:".$_SERVER['DOCUMENT_ROOT']."/comtxt/comments.sqlite";
	$db = new PDO($file) or die("Could not open database");

	// open database file
	$query = "SELECT  * FROM 'com_list' "
		." ORDER BY rowid DESC LIMIT 8";


	// execute query
	$result = $db->query($query) or die("Error in query ".$db->lastErrorMsg());
	$i = 0;

 print'Recent comments contributed: <br />';



	   foreach($result as $fields) {
	 	print  $fields[0].' by ' .$fields[1] ."<a href='" .$fields[2] ."' target='_blank'><b> GO </a> | </b>";
	 	$i = $i + 1;
	 	if ($i == 2) { print '<br />';
			      $i = 0;}
    	}

	unset($db);

?>

To show the comment tracker on a page simply include the script like this at the desired place:


<?php include($_SERVER['DOCUMENT_ROOT'].'/php/com_list.php'); ?>

Conclusion

I know that there are lots of ready to use comment add ins out there. I just wanted it plain and simple without any graphical overhead like smilies and such.
You'll find all the example on this site. When something is not working I'll I probably have something forgotten in the above documentation. In this case or when you have questione (not sure I'm able to answer them -:) feel free to send me a mail to richard@richardhwinter.de .


copyright 2009 - 2017 Richard Winter
Complaints, questions, comments? Contact richard@richardhwinter.de