ACCES INTERZIS | blog de programare si securitate IT


UPDATED ARTICLE

Prin ce se caracterizeaza acest formular de comentarii?

  • scriptul PHP isi creeaza singur tabelul in care va stoca comentariile daca acesta nu exista in baza de date (deci mai putina munca in phpmyadmin)
  • protectie antispam 100% datorita sistemului CAPTCHA integrat
  • toate datele introduse sunt validate server-side (nu bag mana in foc caci inca nu sunt doxa de programare, dar cred ca este securizat destul ca sa nu execute vreun rau-voitor o injectie sql)
  • evidentierea campurilor care contin date invalide
  • pastrarea datelor in campuri atunci cand scriptul detecteaza o eroare
  • background-ul fiecarui comentariu alterneaza de la un comentariu la altul pentru o mai buna vizualizare a comentariilor
  • designul formularului este creat EXCLUSIV din CSS

Asadar, ca sa realizez un formular de cometarii mai intai creez in baza de date tabelul care va stoca toate comentariile.

$q = "CREATE TABLE IF NOT EXISTS ai_commentform(
		comment_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
		name VARCHAR(30) NOT NULL,
		email VARCHAR(30) NOT NULL,
		website VARCHAR(30) NOT NULL,
		comment TEXT NOT NULL,
		date DATETIME NOT NULL,
		ip VARCHAR(30) NOT NULL,
		PRIMARY KEY(comment_id))";

mysql_query($q) or die(mysql_error());

Mai avem nevoie de connect_to_db.inc.php, fisierul care ne conecteaza la baza de date.

<?php
/*
Titlu: Cum fac un formular de comentarii?
Autor: Marian Barbu aka AccesInterzis
Website: http://www.accesinterzis.ro
2010 (c) Toate drepturile rezervate
*/

//-----creez o sesiune pe server pentru a salva in ea codul generat aleatoriu de sistemul CAPTCHA
#1
session_start();

//-----ma conectez la baza de date
#2
include('includes/connect_to_db.inc.php');

//-----infasor in strip_tags() si htmlentities() URL-urile obtinute dinamic ca sa ma asigur ca nu contin cod malitios
#3
$php_self = htmlentities(strip_tags($_SERVER['PHP_SELF']), ENT_QUOTES, 'utf-8');
$referer = (isset($_SERVER['HTTP_REFERER'])) ? htmlentities(strip_tags($_SERVER['HTTP_REFERER']), ENT_QUOTES, 'utf-8') : NULL;

//-----specific EXACT cu ce campuri se va lucra
#4
$required_fields = array('name', 'email', 'website', 'comment', 'security_code', 'add');
$sent_fields = array_keys($_POST);

//------scriptul PHP se executa doar daca cererea a fost facuta de pe aceeasi pagina pe care se afla formularul si doar daca toate campurile formularului au fos trimise
#5
if ($referer == 'http://'.$_SERVER['HTTP_HOST'].$php_self && $required_fields == $sent_fields) {
	//-----initializez array-ul in care voi stoca mesajele de eroare si array-ul in care voi pasa datele din $_POST dupa ce le filtrez
	#5.1
	$errors = array();
	$post = array();

	#5.2
	//Starting data validation
	if (empty($_POST['name'])) {
		$errors['name'] = 'You forgot to enter the <strong>name</strong>.';
	} else {
		$post['name'] = trim($_POST['name']);

		if (ini_get('magic_quotes_gpc')) {
			$post['name'] = stripslashes($post['name']);
		}

		if (strlen($post['name']) < 3) {
			$errors['name'] = 'The <strong>name</strong> is too short.';
		} else {
			if (strlen($post['name']) > 30) {
				$errors['name'] = 'The <strong>name</strong> is too long.';
			} else {
				if (!preg_match('/[a-z0-9_ ]*/i', $post['name'])) {
					$errors['name'] = 'The <strong>name</strong> isn\'t valid.';
				}
			}
		}
	}

	if (empty($_POST['email'])) {
		$errors['email'] = 'You forgot to enter the <strong>email address</strong>.';
	} else {
		$post['email'] = trim($_POST['email']);

		if (ini_get('magic_quotes_gpc')) {
			$post['email'] = stripslashes($post['email']);
		}

		if (strlen($post['email']) < 3) {
			$errors['email'] = 'The <strong>email address</strong> is too short.';
		} else {
			if (strlen($post['email']) > 30) {
				$errors['email'] = 'The <strong>email address</strong> is too long.';
			} else {
				if (!preg_match('/^[a-z0-9][a-z0-9_.]+@[a-z0-9-.]+\.[a-z]{2,4}$/i', $post['email'])) {
					$errors['email'] = 'The <strong>email address</strong> isn\'t valid.';
				}
			}
		}
	}

	if (empty($_POST['website'])) {
		$post['website'] = NULL;
	} else {
		$post['website'] = trim($_POST['website']);

		if (ini_get('magic_quotes_gpc')) {
			$post['website'] = stripslashes($post['website']);
		}

		if (strlen($post['website']) < 7) {
			$errors['website'] = 'The <strong>website</strong> URL is too short.';
		} else {
			if (strlen($post['website']) > 30) {
				$errors['website'] = 'The <strong>website URL</strong> is too long.';
			} else {
				if (!preg_match('/^http:\/\/[a-z0-9.-]+\.[a-z]{2,4}$/i', $post['website'])) {
					$errors['website'] = 'The website URL isn\'t valid.';
				}
			}
		}
	}

	if (empty($_POST['comment'])) {
		$errors['comment'] = 'You forgot to enter the <strong>comment</strong>.';
	} else {
		$post['comment'] = trim($_POST['comment']);

		if (ini_get('magic_quotes_gpc')) {
			$post['comment'] = stripslashes($post['comment']);
		}

		if (strlen($post['comment']) < 2) {
			$errors['comment'] = 'The <strong>comment</strong> is too short.';
		} else {
			if (strlen($post['comment']) > 100000) {
				$errors['comment'] = 'The <strong>comment</strong> is too long.';
			}
		}
	}

	if (empty($_POST['security_code'])) {
		$errors['security_code'] = 'You forgot to enter the <strong>security code</strong>.';
	} else {
		$post['security_code'] = trim($_POST['security_code']);

		if (ini_get('magic_quotes_gpc')) {
			$post['security_code'] = stripslashes($post['security_code']);
		}

		if (strlen($post['security_code']) < 3) {
			$errors['security_code'] = 'The <strong>security code</strong> is too short.';
		} else {
			if (strlen($post['security_code']) > 10) {
				$errors['security_code'] = 'The <strong>security code</strong> is too long.';
			} else {
				if (!preg_match('/^[a-z0-9]*$/i', $post['security_code'])) {
					$errors['security_code'] = 'The <strong>security code</strong> isn\'t valid.';
				} else {
					if ($_SESSION['security_code'] != $_POST['security_code']) {
						$errors['security_code'] = 'The <strong>security code</strong> entered is wrong.';
					}
				}
			}
		}
	}
	//Ending data validation

	//------daca nu exista niciun fel de erori bag datele in baza de date
    #5.3
	if(count($errors) == 0) {
		//-----infasor datele in mysql_real_escape_string() deoarece urmeaza sa interoghez baza de date
		#5.3.1
		foreach ($post as $k => $v) {
			$post[$k] = mysql_real_escape_string($v);
		}

        #5.3.2
		$q = "INSERT INTO ai_commentform(`name`, `email`, `website`, `comment`, `date`, `ip`)"
			."VALUES('".$post['name']."', '".$post['email']."', '".$post['website']."', '".$post['comment']."', NOW(), '".$_SERVER['REMOTE_ADDR']."')";

		#5.3.3
		if (mysql_query($q) == false) {
			$error_message = 'Something is wrong with the server. Your comment wasn\'t added.';
		}
    }

	//-----infasor datele in htmlentities() deoarece urmeaza sa le afisez in formular
	#5.4
	foreach ($post as $k => $v) {
		$post[$k] = htmlentities(stripslashes($v), ENT_QUOTES, 'utf-8');
	}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>How do I make a comment form?</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="How do I make a comment form?" />
<meta name="keywords" content="comment,form,php,script,add,email" />
<meta name="abstract" content="How do I make a comment form?" />
<meta name="author" content="AccesInterzis" />
<meta name="copyright" content="AccesInterzis" />
<meta name="robots" content="index,follow" />
<meta name="revisit-after" content="7 days" />

<style type="text/css">
* {
	margin:0;
	padding:0;
	outline:none;
}

html {
	color:black;
	background-color:white;
	font: normal normal normal 12px  Verdana;
	/*font-style font-variant font-weight font-size font-family*/
}

/*INCEPUT - LINIILE CSS CARE CREEAZA SKINUL FORMULARULUI DE CONTACT*/

div#commentf {
	width:530px;
	margin:0px auto;
}

div#commentf h1 {
	color:black;
	font: normal normal normal 24px  Verdana;
	/*font-style font-variant font-weight font-size font-family*/
	padding-bottom:5px;
}

div#commentf div {
	margin:0 0 5px 0;
}

div#commentf label {
	width:115px;
	float:left;
}

div#commentf label span {
	color:#c00;
}

div#commentf input {
	width:200px;
}

div#commentf textarea {
	width:400px;
	height:150px;
}

div#commentf input, div#commentf textarea {
	border:1px #ccc solid;
}

div#commentf input:hover, div#commentf textarea:hover {
	border:1px #666 solid;
}

div#commentf input#add {
	width:auto;
	color:#FFF;
	background-color:#333;
	border:1px #000 solid !important;
	cursor:pointer;
}

div#commentf input#add:hover {
	color:#333;
	background-color:#fff;
	border:1px #333 solid;
}

/*Inceput - stilurile erorilor*/
div#commentf form#form-itself p {
	color:#c00;
	font-size:10px;
	padding:0 0 0 115px;
	text-align:left;
}

div#commentf div#name_field label,
div#commentf div#email_field label,
div#commentf div#website_field label,
div#commentf div#comment_field label,
div#commentf div#security_code_field label {
	color:#c00;
}

div#commentf div#name_field input,
div#commentf div#email_field input,
div#commentf div#website_field input,
div#commentf div#comment_field textarea,
div#commentf div#security_code_field input {
	border:1px #c00 solid;
	color:#c00;
}

div#commentf div#name_field input:hover,
div#commentf div#email_field input:hover,
div#commentf div#website_field input:hover,
div#commentf div#comment_field textarea:hover,
div#commentf div#security_code_field input:hover {
	border:1px #c00 solid;
}
/*Sfarsit - stilurile erorilor*/

div#comments h1 {
	color:#c00;
	font: normal normal normal 24px  Verdana;
	/*font-style font-variant font-weight font-size font-family*/
	padding-bottom:5px;
}

/*SFARSIT - LINIILE CSS CARE CREEAZA SKINUL FORMULARULUI DE CONTACT*/
</style>
</head>

<body>
<?php
$q = "SELECT name, website, date, comment FROM ai_commentform ORDER BY comment_id DESC";
$result = mysql_query($q) or die(mysql_error());

/*
Cand citesc datele din baza de date le infasor in stripslashes(), htmlentities() si nl2br().
*/
if (mysql_num_rows($result) != 0) {
	echo '<div id="comments">';
	echo '<h1>'.mysql_num_rows($result).' comment(s) so far</h1>';

	$i = 0;
	while ($row = mysql_fetch_array($result)) {
		echo '<p>';
		echo ($row['website'] == '') ? '<strong>'.$row['name'].'</strong>' : '<a href="'.$row['website'].'" title="'.$row['website'].'" target="_blank">'.$row['name'].'</a>';
		echo ' - '.$row['date'];
		echo '</p>';

		echo (is_int($i/2)) ? '<p style="margin-bottom:15px;">' : '<p style="margin-bottom:15px; background:#ccc;">';
		echo nl2br(htmlentities(stripslashes($row['comment']), ENT_QUOTES, 'utf-8'));
		echo '</p>';

		$i++;
	}
	echo '</div>';
}
?>
<div id="commentf">
	<h1>
		<label>&nbsp;</label>
		Leave a comment
	</h1>

	<form action="<?php echo 'http://'.$_SERVER['HTTP_HOST'].$php_self; ?>" method="post" id="form-itself">
		<?php echo (isset($errors['name'])) ? '<p>'.$errors['name'].'</p><div id="name_field">' : '<div>' ; ?>
			<label for="name">Name<span>*</span>:</label>
			<input name="name" type="text" id="name" value="<?php if (isset($post['name'])) echo $post['name']; ?>" />
		</div>

		<?php echo (isset($errors['email'])) ? '<p>'.$errors['email'].'</p><div id="email_field">' : '<div>' ; ?>
			<label for="email">Email<span>*</span>:</label>
			<input name="email" type="text" id="email" value="<?php if (isset($post['email'])) echo $post['email']; ?>" />
		</div>

		<?php echo (isset($errors['website'])) ? '<p>'.$errors['website'].'</p><div id="website_field">' : '<div>' ; ?>
			<label for="website">Website:</label>
			<input name="website" type="text" id="website" value="<?php if (isset($post['website'])) echo $post['website']; ?>" />
		</div>

		<?php echo (isset($errors['comment'])) ? '<p>'.$errors['comment'].'</p><div id="comment_field">' : '<div>' ; ?>
			<label for="comment">Your comment<span>*</span>:</label>
			<textarea name="comment" rows="1" cols="1" id="comment"><?php if (isset($post['comment'])) echo $post['comment']; ?></textarea>
		</div>

		<p>
			<img src="includes/captchaimage.inc.php?width=120&height=40&characters=5" />
		<p>

		<?php echo (isset($errors['security_code'])) ? '<p>'.$errors['security_code'].'</p><div id="security_code_field">' : '<div>' ; ?>
			<label for="security_code">Are you human?<span>*</span></label>
			<input id="security_code" name="security_code" type="text" />
		</div>

		<div>
			<label> &nbsp; </label>
			<input name="add" type="submit" id="add" value="add" />
		</div>
	</form>
</div>
</body>
</html>

Felul in care se integreaza sistemul CAPTCHA in formular il puteti gasi in articolul care prezinta cum se realizeaza un formular de contact.

Pentru un mai bun managment al codului este indicat ca scriptul PHP de deasupra DOCTYPE-ului, care valideaza datele introduse in formular si introduce comentariile in baza de date, sa se bage intr-un fisier include si sa fie apelat prin functia PHP include().

<?php @include('includes/add_comment.inc.php'); ?>

De asemenea, este indicat ca liniile CSS, care creeaza skinul formularului de comentarii, din sectiunea <head> </head> sa fie bagate intr-un fisier CSS extern si apelate cu tagul HTML <link />.

<link href="css/comment_form_design.css" type="text/css" rel="stylesheet" media="all" />

Post to Twitter Publica acest articol pe Twitter

Articole asemanatoare:

Publicat de: admin
Ultima modificare: 17, 2010, 13:13

Etichete
Etichete: , , ,
Categorii: programare


 

Comentarii lasate » (3 Total)

 
  1. Maxi says:

    Foarte interesant , vreau sa fac asa ceva de ceva vreme .

  2. Pork says:

    salut…poti sa imi dai arhiva cu scriptul si instructiunile de folosire?

    Multumesc Anticipat!

  3. florin says:

    buna te rog frumos daca vrei si esti draguta fami tu formularu pentru blogu meu te rog frumos ca eu tot am ancercat dar nu anteleg nimic Multumesc anticipat.

Lasa un comentariu

XHTML: Poti folosi urmatoarele taguri HTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>