PHP

How To Create Comment System with Captcha in PHP MySQL

How To Create Comment System with Captcha in PHP MySQL
Written by Deepak Raj

Hi friends, in this post we are going to learn how to create comment system with captcha in PHP Mysql. Comment is an important part of any kind of blog and website. A CAPTCHA is a kind of challenge-response system designed to differentiate humans from robotic software programs. CAPTCHAs are used as security checks to deter spammers and hackers. we use captcha to secure our website.

How To Create Comment System with Captcha in PHP MySQL

1-Creating Database

  • Open PHPMyAdmin in your Browser
  • Click on Database Tab Display on Topside
  • Give the Database name “comment”.
  • After Creating Database Open it.
  • Click on SQL Tab on Top area
  • Copy the Below Source Code and paste it.
  • Then Click on Go.
-- phpMyAdmin SQL Dump
-- version 4.2.7.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Oct 26, 2018 at 10:40 PM
-- Server version: 5.6.20
-- PHP Version: 5.5.15

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `comment`
--

-- --------------------------------------------------------

--
-- Table structure for table `comment`
--

CREATE TABLE IF NOT EXISTS `comment` (
`commentid` int(11) NOT NULL,
  `name` varchar(30) NOT NULL,
  `content` varchar(300) NOT NULL,
  `comsubid` int(11) NOT NULL,
  `images` varchar(30) NOT NULL
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=17 ;

--
-- Dumping data for table `comment`
--

INSERT INTO `comment` (`commentid`, `name`, `content`, `comsubid`, `images`) VALUES
(16, 'Deep', 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry''s standard dummy text ever since the 1500s,', 15, 'img/p.png'),
(15, 'Mr Raj', 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry''s standard dummy text ever since the 1500s,', 0, 'img/p.png');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `comment`
--
ALTER TABLE `comment`
 ADD PRIMARY KEY (`commentid`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `comment`
--
ALTER TABLE `comment`
MODIFY `commentid` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=17;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

OR Import DB File

After Downloading the source code extract it in your root folder.

  • Open PHPMyAdmin in your Browser
  • Click on Database Tab Display on Topside
  • Give the Database name “comment”.
  • After Creating Database Open it.
  • Click on Import Tab on Top area
  • You can Find db  folder in the Downloaded source code where find comment.sql file then Select it.
  • Then Click on Go.

2- Creating Database Connection

After import Database File then next step is creating a database connection using php copy the below code and save it is as “connection.php”.

<?php
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "";
$mysql_database = "comment";
$prefix = "";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select database");
?>

3 – Creating Index page

in this step, we are going to create an index page where create a commenting form and insert into database and fetch submitted comment in index page. you can simply copy the below source code and save it as index.php in your project folder.

<?php 
session_start();
$errors = '';

if(isset($_POST['submit']))
{
	if(empty($_SESSION['6_letters_code'] ) ||
	  strcmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0)
	{
		$errors .= "\n The captcha code does not match!";
	}
	
	if(empty($errors))
	{
		require_once('connection.php');
		$name=$_POST['name'];
		$content=$_POST['content'];
		$commentid=$_POST['commentid'];
		$images='img/p.png';
		mysql_query("INSERT INTO comment(name, content, images, comsubid)VALUES('$name', '$content', '$images', '$commentid')");
	}
}

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>
<head>
	<title>How To Create Comment System with Captcha in PHP MySQL</title>
	<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
	<link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
					<style>
		body{
			margin-top:65px;
		}
		.well{
			-webkit-box-shadow: -5px 3px 28px 1px rgba(179,179,179,1);
			-moz-box-shadow: -5px 3px 28px 1px rgba(179,179,179,1);
			box-shadow: -5px 3px 28px 1px rgba(179,179,179,1);
			    padding: 50px;
			margin-bottom: 20px;
			background-color: #ffffff;
			border: 1px dotted #a20000;
		}

		.err
		{
			font-family : Verdana, Helvetica, sans-serif;
			font-size : 12px;
			color: red;
		}
		ul
		{
		padding:0;
		margin: 0 0 0 13px;
		padding: 0;
		}
		#commentcontainer
		{
			height:auto;
			width:600px;
			margin:0 auto;
		}
		#commentcontainer img
		{
		float:left;
		border:1px solid #eeeeee;
		padding:5px;
		margin:0 12px 12px 0;
		}
		.clearfix
		{
		clear:both;
		}
		p
		{
		margin:0;
		padding:2px;
		}
		#subcomm img
		{
		height:auto;
		max-width:40px;
		float:left;
		border:1px solid #eeeeee;
		padding:5px;
		margin:5px 5px 5px 5px;
		}

		#subcomm
		{
		float:right;
		height:auto;
		width:497px;
		background-color:#EDEFF4;
		border-bottom:1px solid white;
		}
		#maincomm
		{
		
		border-bottom:1px dotted red;
		padding-bottom:5px;
		margin-bottom:10px;
		}
		#name
		{
		font-weight: bold;
		color: #3B5998;
		text-transform:capitalize;
		}
		#comm a
		{
			text-decoration:none;
			color:#3b5998;
		}
		#comm a:hover
		{
			text-decoration:underline;
		}
</style>	
	
</head>

<body>
	<div class="col-md-3"></div>
	<div class="col-md-6 well">
<?php
require_once('connection.php');
$result3 = mysql_query("SELECT * FROM comment where comsubid=0");
while($row3 = mysql_fetch_array($result3))
{ 
	$id=$row3['commentid'];
	echo '<div id="maincomm">';
	echo '<img width="100px" height="100px" src="'.$row3['images'].'">';
    echo '<p id="name">'.$row3['name'].'</p>';
	echo '<p>'.$row3['content'].'</p>';
	echo '<p id="comm">'.'<a href="index.php?id='.$id.'&#link1">Reply</a>'.'</p>';
	
		$result4 = mysql_query("SELECT * FROM comment where comsubid='$id'");
			while($row4 = mysql_fetch_array($result4))
			{
				echo '<div id="subcomm">';
				echo '<img width="150px" height="150px" src="'.$row4['images'].'">';
				echo '<p id="name">'.$row4['name'].'</p>';
				echo '<p>'.$row4['content'].'</p>';
				echo '<div class="clearfix"></div>';
				echo '</div>';
			}
	echo '<div class="clearfix"></div>';
	echo '</div>';
}
?>
<div class="clearfix"></div>



<a id="link1">
<form method="POST" name="" 
action="index.php"> 
<table align="center">
  <tr>
    <td width="265">
		<ul>
		<?php
		if(!empty($errors)){
		echo "<li class='err'>".($errors)."</li>";
		}
		?>
		</ul>	</td>
    <td width="57">&nbsp;</td>
  </tr>
   <tr>
    <td colspan="2">
		Name:<br>
		<input name="commentid" type="hidden" value="<?php echo $_GET['id'] ?>">
		<input name="name" type="text" class="form-control"><br>
		Content:<br>
		<textarea name="content" style="width: 316px;" class="form-control"></textarea>
	</td>
   </tr>
  <tr>
  <tr>
    <td> <img src="generatecaptcha.php?rand=<?php echo rand(); ?>" id='captchaimg' > </td>
    <td> <a href='javascript: refreshCaptcha();'><img src="refresh.png"></a> </td>
  </tr>
  <tr>
    <td colspan="2">Enter the code above here :
      <input id="6_letters_code" name="6_letters_code" type="text" class="form-control"></td>
    </tr>
  <tr>
    <td colspan="2"><br /><input class="btn btn-success" type="submit" value="Submit" name='submit'></td>
    </tr>
</table>
</form>
</a>
<script language='JavaScript' type='text/javascript'>
function refreshCaptcha()
{
	var img = document.images['captchaimg'];
	img.src = img.src.substring(0,img.src.lastIndexOf("?"))+"?rand="+Math.random()*1000;
}
</script>
</body>
</html>

4-  Creating CAPTCHA

in this step, we are creating CAPTCHA using PHP . This script includes the creation of captcha and rendering it to the page using PHP.  here the source code copy and save it as generatecaptcha.php

<?php 

session_start();
//Settings: You can customize the captcha here
$image_width = 280;
$image_height = 40;
$characters_on_image = 6;
$font = './fonts/monofont.ttf';

//The characters that can be used in the CAPTCHA code.
//avoid confusing characters (l 1 and i for example)
$possible_letters = '23456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ';
$random_dots = 30;
$random_lines = 20;
$captcha_text_color="0x142864";
$captcha_noice_color = "0x142864";

$code = '';


$i = 0;
while ($i < $characters_on_image) { 
$code .= substr($possible_letters, mt_rand(0, strlen($possible_letters)-1), 1);
$i++;
}


$font_size = $image_height * .75;
$image = @imagecreate($image_width, $image_height);


/* setting the background, text and noise colours here */
$background_color = imagecolorallocate($image, 255, 255, 255);

$arr_text_color = hexrgb($captcha_text_color);
$text_color = imagecolorallocate($image, $arr_text_color['red'], 
		$arr_text_color['green'], $arr_text_color['blue']);

$arr_noice_color = hexrgb($captcha_noice_color);
$image_noise_color = imagecolorallocate($image, $arr_noice_color['red'], 
		$arr_noice_color['green'], $arr_noice_color['blue']);


/* generating the dots randomly in background */
for( $i=0; $i<$random_dots; $i++ ) {
imagefilledellipse($image, mt_rand(0,$image_width),
 mt_rand(0,$image_height), 2, 3, $image_noise_color);
}


/* generating lines randomly in background of image */
for( $i=0; $i<$random_lines; $i++ ) {
imageline($image, mt_rand(0,$image_width), mt_rand(0,$image_height),
 mt_rand(0,$image_width), mt_rand(0,$image_height), $image_noise_color);
}


/* create a text box and add 6 letters code in it */
$textbox = imagettfbbox($font_size, 0, $font, $code); 
$x = ($image_width - $textbox[4])/2;
$y = ($image_height - $textbox[5])/2;
imagettftext($image, $font_size, 0, $x, $y, $text_color, $font , $code);


/* Show captcha image in the page html page */
header('Content-Type: image/jpeg');// defining the image type to be shown in browser widow
imagejpeg($image);//showing the image
imagedestroy($image);//destroying the image instance
$_SESSION['6_letters_code'] = $code;

function hexrgb ($hexstr)
{
  $int = hexdec($hexstr);

  return array("red" => 0xFF & ($int >> 0x10),
               "green" => 0xFF & ($int >> 0x8),
               "blue" => 0xFF & $int);
}
?>

If you facing any type of problem with this source code then you can Download the Complete source code in zip Formate by clicking the below button Download Now otherwise you can send Comment.

About the author

Deepak Raj

Hi, This is Deepak Raj from Sourcecodessite.com.I am a Web Developer, Blogger, Online Instructor and SEO consultant who has been working online for last 4 years and he is running several successful websites on the internet.

Leave a Comment