Basic Comment System available for Download

Hi there,

First of all I am not an expert in the field (YET :wink: ) but I’ve created a comment system using PHP/MySQL from the things that I’ve learned so far. My aim was just to figure out how comment system works and I think I’ve achieved it 8)

For beginners feel free to download / study and improve it but If you are an expert then please give your comments / recommendations / suggestions.

I’ve also used comments extensively so that you easily figure out what’s going on in the scripts. But if you are still stuck somewhere in the code please comment below.

If you want to download all the files in a ZIP format then click on the link below:

Here goes the code :stuck_out_tongue:

index.php
[php]<?php
header(“Location: login.php”);
?>[/php]

login.php
[php]

<?php session_start(); require_once('functions.php'); if (isset($_SESSION['username']) ){ header("Location: comment.php"); } ?> Log In <?php if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['username']) && !empty($_POST['password']) && isset($_POST['login']) ){ $conn = db_connect(); $username = mysqli_real_escape_string($conn, safe_output($_POST['username'])); $pass = secure_password($conn, ($_POST['password'])); $result = query_login_user($conn, $username, $pass); /* If the above query was successfull user will be redirected to the 'Comments Page' otherwise the following code will execute. */ if(is_null($result)) { $result = "Invalid Username / Password, Try again"; } } ?> <?php if(isset($result)) {
           echo $result;
        }

?>

<form action="" method="POST" >
    <table>
        <tr>
            <td><label for="username">Username: </label> </td>
            <td><input type="text" name="username" id="username" /></td>
        </tr>

        <tr>
            <td><label for="password">Password: </label></td>
            <td><input type="password" name="password" id="password" /></td>
        </tr>
    </table>

        <input type="submit" value="Log In" name="login" /> 
        &nbsp;  &nbsp; &nbsp; &nbsp;
        <input type="button" value="Register" onClick="location.href='register.php'" />
</form>
<?php if (isset($close_conn)){
        mysqli_close($conn); 

      }

?>

[/php]

functions.php

[php]<?php

/* Change ‘Asia/Karachi’ according to your timezone. */
date_default_timezone_set(‘Asia/Karachi’);

function db_connect(){

/* Replace the values of 

		localhost
		username 
		password
		database

 with your own details */

$host = 'localhost';
$user = 'tanzeelniazi';
$pass = 'abc';
$db = 'phphelp';

$conn = @mysqli_connect($host, $user, $pass, $db);

if (mysqli_connect_errno()) { die ("Can't Connect to Database");}

return $conn;

}

/* Function to strip out bad things users enter via forms */
function safe_output($form){

		$form = strip_tags($form);
		$form = trim($form);
		$form = htmlspecialchars($form);

		return $form;
}	

/*
Function to secure user’s password using BlowFish Hashing Algorithm
If you are using a version prior to PHP 5.3 then It will not work, therefore you need to change the hashing algorithm.

*/
function secure_password($conn, $password){

	$hash_format = "$2y$10$";
	$salt = md5("Tanz33lN!@zi@SpinZRphp");

	$salt_format = $hash_format . $salt;
	$hash = crypt($password, $salt_format);

	return $hash;
}	

/*
This function will check usernames and email addresses in the database. If any existing record is found it will return a string otherwise it will return NULL if no record is found.
*/
function query_check_user($conn, $username, $email ){

	$query = "SELECT * FROM users 
							WHERE username = '{$username}'
			 ";

	$results = mysqli_query($conn, $query);

	if ($results && mysqli_affected_rows($conn) == 1){

		$existing_user = "Username Already Exists, choose another one";

		return $existing_user;
	} 

	$query = "SELECT * FROM users 
							WHERE email = '{$email}'
			 ";

	$results = mysqli_query($conn, $query);

	if ($results && mysqli_affected_rows($conn) == 1){

		$existing_user = "Email Already Exists, choose another one";

		return $existing_user;
	} 

	
	return NULL;
	
}

/*
Once the ‘query_check_user’ function returns NULL. This function will add a new user to the database and will return TRUE if sucessful.
*/
function query_add_user($conn, $name, $username,
$email, $pass, $vericode = 0){

$query = "INSERT INTO
					users 
				VALUES (
					NULL,
					'{$name}',
					'{$username}',
					'{$pass}',
					'{$email}',
					'unverified',
					'{$vericode}'
					)
			";
	
	$results = mysqli_query($conn, $query);
	
	if (!$results) {

		die(mysqli_error($conn));
	}

	return TRUE;
}

/*
Once the ‘query_add_user’ function succeeds. This function will select the newly added user and will return an array with variables likes name, username, email and vericode. So that it can be used to verify the email address by sending an email to the email address specified during registration.

*/
function query_verify_user($conn, $username, $email, $pass){

	$query = "SELECT * FROM users 
					WHERE username = '{$username}'	AND 
							password = '{$pass}' AND 
							email = '{$email}'
			 ";

	
	$results = mysqli_query($conn, $query);

	if ($results && mysqli_affected_rows($conn) == 1){

		while ($user = mysqli_fetch_assoc($results)){
				
			return $user;				
		}

	} else { return NULL; }
}

/*
When the user click on the link sent to them via email. This function will update thier status from Unverified to Verified.

*/
function query_update_user($conn, $email, $vericode){

	$query = "UPDATE users 
					SET 
						status = 'verified'
					WHERE 
						email = '{$email}' AND
						vericode = '{$vericode}'
			 ";

	$results = mysqli_query($conn, $query);

	if ($results && mysqli_affected_rows($conn) == 1){

		return $results;				
	}

	 else { return NULL; }
}

/*
This function will give administrator the ability to block a user from accessing their account and they will be unable to post new comments on the comments page.

Remember Users are not deleted permanently from the database but only their status will be changed from 'Verified' to 'Deleted'.

*/
function query_delete_user($conn, $user){

	$query = "UPDATE users 
					SET 
						status = 'deleted'
					WHERE 
						username = '{$user}'
			 ";

	$results = mysqli_query($conn, $query);

	if (!$results){

			die(mysqli_error($conn));			
	}

	 return NULL; 
}

/*
This function will check for the users who are attempting to login.

If their status is 'Unverified' or 'Deleted' it will return a string to the function and they will not be able to login.

If login was successful a session variable 'username' will be created and they will be redirected to the comments page. 

*/

function query_login_user($conn, $username, $pass){

	$query = "SELECT * FROM users 
					WHERE username = '{$username}'	AND 
							password = '{$pass}' AND
							status = 'unverified'
			 ";


	$results = mysqli_query($conn, $query);

	if ($results && mysqli_affected_rows($conn) == 1){

		$acc_status = 	'<p>Your account is not yet verified,
							please contact the site administrator.
						</p>
						';

		return $acc_status;
	} 

	$query = "SELECT * FROM users 
					WHERE username = '{$username}'	AND 
							password = '{$pass}' AND
							status = 'deleted'
			 ";


	$results = mysqli_query($conn, $query);

	if ($results && mysqli_affected_rows($conn) == 1){

		$acc_status = 	'<p>Your account has been blocked, 
							please contact the site administrator.
						</p>
						';

		return $acc_status;
	} 

	$query = "SELECT * FROM users 
					WHERE username = '{$username}'	AND 
							password = '{$pass}' AND
							status = 'verified'
			 ";


	$results = mysqli_query($conn, $query);

	if ($results && mysqli_affected_rows($conn) == 1){

		$_SESSION['username'] = $user['username'];
		header("Location: comment.php");				
	} else { return NULL; }
}

/*
This function will give users the ability to post comments on the comments page. All comments will be ‘Unapproved’ by default except for the admin.

Then the admin has to manually approve all the comments posted by other users.

*/
function query_insert_comment($conn, $username, $comment, $time,
$status = ‘Unapproved’){

 $query = "INSERT INTO comments
              VALUES (NULL, '{$username}', '{$comment}', '{$time}', '{$status}'
            )";

 $results = mysqli_query($conn, $query);
 if(!$results) {die();}

 return mysqli_affected_rows($conn);

}

/*
This function will fetch all the comments posted on in the comments table so far and will return an array.

*/
function query_fetch_comments($conn){

$query = "SELECT * FROM comments ORDER BY id DESC";

$results = mysqli_query($conn, $query);

if(!$results) {die();}

	while($comment = mysqli_fetch_assoc($results))
	{
    	$id[] 		= $comment['id'];
     	$uname[] 		= $comment['username'];
     	$ucomment[]	= $comment['comment'];
   		$ctime[]		= $comment['comment_time'];
   		$status[]		= $comment['status'];
   		
	}
	
	if (mysqli_affected_rows($conn) > 0){

	return $comments = array('id' => $id,
							 'uname' => $uname,
							 'ucomment' => $ucomment,
							 'ctime' => $ctime,
							 'status' => $status
							 );
	}
}

/*
Gives admin the ability to delete comments.

*/
function query_delete_comment($conn, $id){

$query = "DELETE FROM comments WHERE id = {$id}";

$results = mysqli_query($conn, $query);

if(!$results) {die();}

	return NULL;
}

/*
Gives admin the ability to approve / un-approve comments.

*/
function query_approve_comment($conn, $id, $status){

$query = "UPDATE comments 
				SET status = '{$status}'
				WHERE id = {$id}";

$results = mysqli_query($conn, $query);

if(!$results) {die();}

	return NULL;
}

/*
If a user’s status is set to ‘Deleted’ his comment will be set to ‘Unapproved’ and username for the comment will be set to ‘Anonymous’.

It will not affect all the previous comments of the users but only a particular comment.

*/
function query_anonymous_comment($conn, $username, $id){

$query = "UPDATE comments 
				SET
				username = 'Anonymous',
				status = 'Unapproved'

				WHERE id = {$id}";

$results = mysqli_query($conn, $query);

if(!$results) {die();}

	return NULL;
}

?>[/php]

register.php
[php]<?php

session_start();
require_once(‘functions.php’);

?>

Register for an Account <?php if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['name']) && !empty($_POST['username']) && !empty($_POST['password']) && !empty($_POST['cpassword']) && isset($_POST['SbtReg']) ) { $conn = db_connect(); $name = safe_output($_POST['name']); $username = safe_output($_POST['username']); $email = safe_output($_POST['email']); $pass = secure_password($conn, ($_POST['password'])); $cpass = secure_password($conn, ($_POST['cpassword'])); /* basic email validation by php */ if(filter_var($email, FILTER_VALIDATE_EMAIL)) { if ($pass === $cpass) { $close_conn = NULL; $conn = db_connect(); $name = mysqli_real_escape_string($conn, $name); $username = mysqli_real_escape_string($conn, $username); $email = mysqli_real_escape_string($conn, $email); $pass = mysqli_real_escape_string($conn, $pass); $result = query_check_user($conn, $username, $email); /* If a string is returned back from the query, it means either the username or email address was already available was in the database */ if(is_string($result)){ echo $result; } else { /* If you don't want email verification just comment out the following line and delete the $vericode variable from 'query_add_user' function. */ $vericode = rand(1000, 9999); $result = query_add_user($conn, $name, $username, $email, $pass, $vericode); /* Once the 'query_add_user' function succeeds. The following function will select the newly added user and will return an array. */ $result = query_verify_user($conn, $username, $email, $pass); if (is_array($result)){ $_SESSION['name'] = $result['name']; $_SESSION['username'] = $result['username']; $_SESSION['email'] = $result['email']; $_SESSION['vericode'] = $result['vericode']; /* If you have disabled email verification the following IF statement will evaluate to true and will redirect the user to comments page */ if ($_SESSION['vericode'] == 0) { header('Location: comment.php'); } header('Location: verify.php'); } } } else { echo "Passwords are not same"; } } else { echo "Email Not Valid"; } } ?>
          <tr>
              <td><label for="username">Username: </label> </td>
              <td><input type="text" name="username" id="username" /> </td>
          </tr>

          <tr>
            <td><label for="email">Email Address: </label> </td>
            <td><input type="text" name="email" id="email" /> </td>
          </tr>

          <tr>
              <td><label for="password">Password: </label> </td>
              <td><input type="password" name="password" id="password" /> </td>
          </tr>

          <tr>
            <td><label for="cpassword">Confirm Password: </label></td>
            <td><input type="password" name="cpassword" id="cpassword" />
            </td>
          </tr>
      </table>

     <input type="submit" name="SbtReg" value="Register" />
  </form>
<?php if (isset($close_conn)){ mysqli_close($conn); } ?> [/php]

verify.php
[php]<?php

session_start();
require_once(‘functions.php’);
$conn = db_connect();
?>

Verify Your Account <?php
  if (isset($_SESSION['name']) &&
      isset($_SESSION['username']) &&
      isset($_SESSION['email']) &&
      isset($_SESSION['vericode'])
    )

  {
      
      $name = $_SESSION['name'];
      $to = $_SESSION['email'];
      $vericode = $_SESSION['vericode'];
      
      /* Change the following variables according to your site specifications */

      $my_site = "PHP Help";  
      $site_add = "http://localhost/comment/"; 
      $subject = "Email Activation requried for {$my_site}";
      $headers = "From: [email protected] \r\n";
      $headers .= "Reply-To: [email protected] \r\n";
      $headers .= "MIME-Version: 1.0\r\n";
      $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

      $message = '<b>Hello ' . $name . ' </b> <br /><br />
                  Thank you for your interest in ' . $my_site . ' 
                  We need to <span style="color: red;"> CONFIRM </span> your request first. <br /> 
                  <br />

                  IMPORTANT: all you need to do is click the link
                  below: <br /> <br /> <b>' . 

                 $site_add . 
                 'verify.php?email='.
                 $to . '&vericode=' . $vericode . 

                 ' <br /> <br /> Click the link above and your account will be activated. If you can\'t use the above mentioned link then click on the link below and enter your email address and  <b><span style="color: blue;">' . $vericode . '</span></b>  in the code field to activate your account.<br /> <br />' .

                      $site_add .'verify.php' .

                  '<br /><br />If you do not want to proceed, simply ignore this message. <br /> <br />

                  
                  Regards, <br />

                  Tanzeel Niazi <br />
                  [email protected] <br />
                  www.spinzr.com <br />
                ';

   if (mail($to, $subject , $message, $headers)) {

     echo 
        ' <h3>Thanks for your registration but we need to verify your account. <br /> An email has been sent to your email address. Please click on the link given in the email to activate your account.</h3> 

          <h3><a href="login.php"> Click Here </a> to go to the homepage </h3>
        ';

      /* Destroying the session so that users can't access the page variables on multiple page refreshes */

      session_destroy();
      $_SESSION = array();
      
    }

}

else {

    if( $_SERVER['REQUEST_METHOD'] == 'GET' &&
        isset($_GET['email']) &&
        isset($_GET['vericode']) &&
        !empty($_GET['email']) &&
        !empty($_GET['vericode'])
      ) {


        /* Ensuring if user doesn't use query string, then information gets submitted properly via form */

        $result = query_update_user($conn, 
                                      urldecode($_GET['email']),
                                      urldecode($_GET['vericode'])
                                      );

        if (is_null($result)){

            $_GET = array();
            $_SESSION['status'] = "
                        <h3> Sorry Invalid email / verfication code, Please try again or contact the site administrator
                        </h3>
                      ";
            header("Location: verify.php");

        } 

        else { 
                echo '<h3> Thank You! Your email has been verified.
                          <br /> Please <a href="login.php">click here </a> to go to Login Page. 
                      </h3>';
          }

    }
    else 
    {

        /* If a user has entered wrong email / verfication code at least once then the IF statement will run otherwise ELSE will execute */

         if (isset($_SESSION['status'])){

            echo $_SESSION['status'];
            unset($_SESSION['status']);
            
           }
          else {

            echo "<h1> Please enter the following details. </h1>";

          }

      /* If a user got to this page directly without any query string then He/She will see the following HTML form.

      The Closing Curly Braces are located after the HTML form 

      */

?>

Name:




          <tr>
              <td>
                <label for="vericode">Verification Code: </label>
              </td>
              <td>
               <input type="text" name="vericode" id="vericode" />
              </td>
          </tr>
      </table>
      <p><input type="submit" value="Verify" name="verify" /></p>
    </form>
<?php } } ?> <?php if (isset($close_conn)){
        mysqli_close($conn); 

      }

?>

[/php]

Email:


comments.php
[php]<?php

session_start();
require_once(‘functions.php’);

if(!$_SESSION[‘username’]){
header (‘location: login.php’);
}

$conn = db_connect();
?>

<?php echo "Logout
"; $username = $_SESSION['username']; /* If this IF statement evaluates to true the comment will be deleted against the id received though GET method. Username must be 'admin' otherwise the IF condition will be false */ if ($_SERVER['REQUEST_METHOD'] == 'GET' && !empty($_GET['delc']) && $_SESSION['username'] == 'admin' ){ query_delete_comment($conn, $_GET['delc']); } /* If this IF statement evaluates to true the user's status will be set to 'deleted' against the id received though GET method and comment will get 'Unapproved'. Username must be 'admin' otherwise the IF condition will be false */ if ($_SERVER['REQUEST_METHOD'] == 'GET' && !empty($_GET['delusr']) && $_SESSION['username'] == 'admin' ){ list($id, $username) = explode("_", $_GET['delusr']); query_delete_user($conn, $username); query_anonymous_comment($conn, $username, $id); } /* This IF statement will approve / un-approve users' comments. */ if ($_SERVER['REQUEST_METHOD'] == 'GET' && !empty($_GET['apcomnt']) && $_SESSION['username'] == 'admin' ){ list($id, $status) = explode("_", $_GET['apcomnt']); if ($status == 'Approved'){ query_approve_comment($conn, $id, 'Unapproved'); } if ($status == 'Unapproved'){ query_approve_comment($conn, $id, 'Approved'); } } /* Submit users' comments to the database */ if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['comment']) ){ if ($conn = db_connect()){ $today = date("Y-m-d h:i:s A"); $comment = mysqli_real_escape_string($conn, safe_output($_POST['comment'])); if ($_SESSION['username'] == 'admin'){ query_insert_comment($conn, $username, $comment, $today, 'Approved'); } else { query_insert_comment($conn, $username, $comment, $today); $thanks = "Thanks Your Comment has been submitted for moderation, Your will see it after approval"; } } } /* The following lines of code will fetch users' comment from the database in reverse order */ $comments = query_fetch_comments($conn); $count = count($comments['uname']); for ($i = 0 ; $i <= $count ; $i++) { /* If this IF statement evaluates to TRUE, all the comments in the database will be shown to the site admin. */ if (isset($comments['uname'][$i]) && $_SESSION['username'] == 'admin' ) { if ($comments['uname'][$i] == 'admin') { $_SESSION['username'] = 'SuperAdmin'; } echo "
Comment Posted by {$comments['uname'][$i]} on {$comments['ctime'][$i]}
{$comments['ucomment'][$i]}
"; echo "Delete Comment || "; if ($_SESSION['username'] == 'admin') { if ($comments['uname'][$i] != 'Anonymous'){ echo "Delete User || "; } } echo "{$comments['status'][$i]} Comment || "; $_SESSION['username'] = 'admin'; } /* If user is not a site admin then the following IF statement will evaluate to true and he / she will only see the approved comments. */ if (isset($comments['uname'][$i]) && $comments['status'][$i] == 'Approved' && $_SESSION['username'] != 'admin' ) { echo "
Comment Posted by {$comments['uname'][$i]} on {$comments['ctime'][$i]}
{$comments['ucomment'][$i]}
"; } } ?> Comment Box
    <tr>
        <td><label for="comment">Comment: </label></td>
        <td><textarea name="comment" cols="25" rows="7" id="comment"></textarea></td>
    </tr>
    
    <tr>
      <td colspan="2"><input type="submit" name="submit" value="Comment" /> </td>
    </tr>
  
  </table>
</form>
<?php if(isset($thanks)) { echo $thanks; } ?> <?php if (isset($close_conn)){
        mysqli_close($conn); 

      }

?>

[/php]

logout.php
[php]<?php

	session_start();
	session_destroy();
	$_SESSION = array();

	header ('Location: login.php');

?>[/php]

sql_queries.sql

[code]CREATE TABLE users (

id INT(11) AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
username VARCHAR(30) NOT NULL,
password VARCHAR(100) NOT NULL,
email VARCHAR(200) NOT NULL,
status VARCHAR(10) NOT NULL,
vericode VARCHAR(5) NOT NULL,
PRIMARY KEY (id)
);

CREATE TABLE comments (

id INT(11) AUTO_INCREMENT,
username VARCHAR(30) NOT NULL,
comment VARCHAR(250) NOT NULL,
comment_time VARCHAR(25) NOT NULL,
status VARCHAR(15) NOT NULL,
PRIMARY KEY (id)
);[/code]

Name: " />

Tanzeelniazi, thanks for sharing.

I just enabled attachments for Members, so you don’t have to go through the trouble of finding places to host small attachments.

Thank you very much phphelp.

Sponsor our Newsletter | Privacy Policy | Terms of Service