<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>ACCES INTERZIS &#187; HTML</title>
	<atom:link href="http://www.accesinterzis.ro/index.php/tag/html/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.accesinterzis.ro</link>
	<description>Just another WordPress weblog</description>
	<lastBuildDate>Tue, 20 Apr 2010 12:08:34 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<item>
		<title>Cum fac un formular de autentificare a utilizatorilor? (versiunea 2)</title>
		<link>http://www.accesinterzis.ro/index.php/web/cum-fac-un-formular-de-autentificare-a-utilizatorilor-versiunea-2/</link>
		<comments>http://www.accesinterzis.ro/index.php/web/cum-fac-un-formular-de-autentificare-a-utilizatorilor-versiunea-2/#comments</comments>
		<pubDate>Wed, 17 Mar 2010 13:44:39 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[web]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.accesinterzis.ro/?p=387</guid>
		<description><![CDATA[Scripturile PHP apelate prin functia include() le gasiti in articolul despre versiunea 2 a formularului de contact.
Interogarea SQL care creeaza tabelul in care se vor stoca logurile despre autentificarile esuate sau reusite o gasiti in articolul despre prima versiune a formularului de autentificare a utilizatorilor.

loginf.php

&#60;?php
/*
Cum fac un formular de autentificare a utilizatorilor? (versiunea 2)
Autor: Marian [...]


<strong>Articole asemanatoare:<ul><li><a href='http://www.accesinterzis.ro/index.php/web/cum-fac-un-formular-de-inregistrare-a-utilizatorilor-versiunea-2/' rel='bookmark' title='Permanent Link: Cum fac un formular de inregistrare a utilizatorilor? (versiunea 2)'>Cum fac un formular de inregistrare a utilizatorilor? (versiunea 2)</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-autentificare-a-utilizatorilor/' rel='bookmark' title='Permanent Link: Cum fac un formular de autentificare a utilizatorilor?'>Cum fac un formular de autentificare a utilizatorilor?</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-contact-versiunea-2/' rel='bookmark' title='Permanent Link: Cum fac un formular de contact? (versiunea 2)'>Cum fac un formular de contact? (versiunea 2)</a></li>
</ul>]]></description>
			<content:encoded><![CDATA[<p>Scripturile PHP apelate prin functia include() le gasiti in <a title="Cum fac un formular de contact? (versiunea 2)" href="http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-contact-versiunea-2/" target="_blank">articolul despre versiunea 2 a formularului de contact</a>.<br />
Interogarea SQL care creeaza tabelul in care se vor stoca logurile despre autentificarile esuate sau reusite o gasiti in <a title="Cum fac un formular de autentificare a utilizatorilor?" href="http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-autentificare-a-utilizatorilor/" target="_blank">articolul despre prima versiune a formularului de autentificare a utilizatorilor</a>.</p>
<p><span id="more-387"></span></p>
<p><strong>loginf.php</strong></p>
<pre class="brush: php;">
&lt;?php
/*
Cum fac un formular de autentificare a utilizatorilor? (versiunea 2)
Autor: Marian Barbu aka AccesInterzis
Website: http://www.accesinterzis.ro
2010 (c) Toate drepturile rezervate
*/

//-----specific EXACT cu ce campuri se va lucra
#1
$required_fields = array('username', 'password', 'login');
$sent_fields = array_keys($_POST);

//-----creez o sesiune pe server pentru a salva in ea, in caz ca autentificarea reuseste, numele utilizatorului si browserul si sistemul de operare folosite de utilizator
#2
session_start();

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

//-----incarc fisierele include
#3.1
include('includes/validators.inc.php');
include('includes/filter_it.inc.php');
include('includes/validate_form.inc.php');
include('includes/filtered_urls_and_cookies.inc.php');

//------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
#4
if ($referer == 'http://'.$_SERVER['HTTP_HOST'].$php_self &amp;&amp; $required_fields == $sent_fields) {
	//-----procesez datele din formular; rezultatul va fi o lista de erori, o lista cu datele nevalide, o lista cu datele valide
	#5
	include('includes/process_form.inc.php');

	//-----infasor datele VALIDE in mysql_real_escape_string() deoarece urmeaza sa interoghez baza de date
	#6
	$processed_form['good_data'] = filter_it($processed_form['good_data'], array('mysql_real_escape_string'));

	//-----BEGIN - DATA HANDLING
	#7
	if (isset($processed_form['good_data']['username']) &amp;&amp; isset($processed_form['good_data']['password'])) {
		$q = &quot;SELECT username FROM ai_registrationform WHERE username='&quot;.$processed_form['good_data']['username'].&quot;' AND password=SHA('&quot;.$processed_form['good_data']['password'].&quot;')&quot;;
		$result = mysql_query($q) or die(mysql_error());
		$row = mysql_fetch_array($result);

		if ($row == false) {
			//-----daca datele de logare sunt valide dar nu se regasesc in baza de date se va inregistra in tabelul de loguri un log despre aceasta autentificare esuata
			$q2 = &quot;INSERT INTO ai_authentication_logs(`username`, `password`, `server_authentication_date`, `client_authentication_date`, `ip`, `browser_os`, `screen_resolution`, `status`)&quot;
				 .&quot;VALUES('&quot;.$processed_form['good_data']['username'].&quot;', '&quot;.$processed_form['good_data']['password'].&quot;', NOW(), '&quot;.$cookie['client_authentication_date'].&quot;', '&quot;.$_SERVER['REMOTE_ADDR'].&quot;', '&quot;.$browser_os.&quot;', '&quot;.$cookie['screen_resolution'].&quot;', 'failed')&quot;;

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

			$processed_form['issues']['username'] = 'Your login data are wrong.';
			$processed_form['issues']['password'] = '';
		}
	}
	//-----END - DATA HANDLING

	//-----daca nu exista niciun fel de erori si autentificarea s-a efetuat cu succes
    #8
	if(count($processed_form['issues']) == 0) {
		//-----salvez in tabelul de loguri un log despre autetificare
		#8.1
		$q = &quot;INSERT INTO ai_authentication_logs(`username`, `password`, `server_authentication_date`, `client_authentication_date`, `ip`, `browser_os`, `screen_resolution`, `status`)&quot;
		     .&quot;VALUES('&quot;.$processed_form['good_data']['username'].&quot;', SHA('&quot;.$processed_form['good_data']['password'].&quot;'), NOW(), '&quot;.$cookie['client_authentication_date'].&quot;', '&quot;.$_SERVER['REMOTE_ADDR'].&quot;', '&quot;.$browser_os.&quot;', '&quot;.$cookie['screen_resolution'].&quot;', 'succesful')&quot;;

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

		//-----salvez in sesiune numele utilizatorului si numele browserului si sistemului de operare pe care le foloseste
		#8.2
		$_SESSION['username'] = $row['username'];
		$_SESSION['browser_os'] = sha1($_SERVER['HTTP_USER_AGENT']);

		//-----redirectez utilizatorul de pe pagina de login pe pagina principala a sectiunii de administrare
		#8.3
		header('Location:http://'.$_SERVER['HTTP_HOST'].dirname($php_self).'/backend.php');
		exit();
	}

	//-----infasor datele in htmlentities() deoarece urmeaza sa le afisez in formular
	#9
	$get_my_fields = filter_it($get_my_fields, array('htmlentities'));
}
?&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;How do I make a login form?&lt;/title&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot; /&gt;
&lt;meta name=&quot;description&quot; content=&quot;How do I make a login form?&quot; /&gt;
&lt;meta name=&quot;keywords&quot; content=&quot;login,form,php,script,mysql,database,user,backend,admin,section,cms&quot; /&gt;
&lt;meta name=&quot;abstract&quot; content=&quot;How do I make a login form?&quot; /&gt;
&lt;meta name=&quot;author&quot; content=&quot;AccesInterzis&quot; /&gt;
&lt;meta name=&quot;copyright&quot; content=&quot;AccesInterzis&quot; /&gt;
&lt;meta name=&quot;robots&quot; content=&quot;index,follow&quot; /&gt;
&lt;meta name=&quot;revisit-after&quot; content=&quot;7 days&quot; /&gt;

&lt;style type=&quot;text/css&quot;&gt;
* {
	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 AUTENTIFICARE*/

div#loginf {
	width:285px;
	margin:0px auto;
}

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

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

div#loginf label {
	width:80px;
	float:left;
}

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

div#loginf input {
	width:200px;
}

div#loginf textarea {
	width:300px;
	height:150px;
}

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

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

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

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

/*Inceput - stilurile erorilor*/

div#loginf p {
	color:#c00;
	padding:0 0 0 80px;
	font-size:10px;
	text-align:left;
}

div#loginf div#username_field label,
div#loginf div#password_field label {
	color:#c00;
}

div#loginf div#username_field input,
div#loginf div#password_field input {
	border:1px #c00 solid;
	color:#c00;
}

div#loginf div#username_field input:hover,
div#loginf div#password_field input:hover {
	border:1px #c00 solid;
}

/*Sfarsit - stilurile erorilor*/

/*SFARSIT - LINIILE CSS CARE CREEAZA SKINUL FORMULARULUI DE AUTENTIFICARE*/
&lt;/style&gt;

&lt;script type=&quot;text/javascript&quot;&gt;
/*
Creez cookie-urile care vor stoca date despre utilizator.
Aceste cookie-uri se creeaza atunci cand se deschide prima oara pagina de login.
De abia cand se reincarca pagina, adica cand utilizatorul apasa butonul &quot;login&quot;, scriptul PHP
se poate folosi de aceste cookie-uri.
*/
document.cookie = 'screen_resolution=' + screen.width + '*' + screen.height + ';';

var current_date = new Date();
var year = current_date.getFullYear();
var month = current_date.getMonth();
var day = current_date.getDate();
var hour = current_date.getHours();
var minutes = current_date.getMinutes();
var seconds = current_date.getSeconds();
var current_date = year + '-' + month + '-' + day + ' ' + hour + ':' + minutes + ':' + seconds;
document.cookie = 'client_authentication_date=' + current_date + ';';
&lt;/script&gt;
&lt;/head&gt;

&lt;body&gt;
&lt;div id=&quot;loginf&quot;&gt;
	&lt;h1&gt;
		&lt;label&gt;&amp;nbsp;&lt;/label&gt;
		Login
	&lt;/h1&gt;

	&lt;form action=&quot;&lt;?php echo 'http://'.$_SERVER['HTTP_HOST'].$php_self; ?&gt;&quot; method=&quot;post&quot;&gt;
		&lt;?php echo (isset($processed_form['issues']['username'])) ? '&lt;p&gt;'.$processed_form['issues']['username'].'&lt;/p&gt;&lt;div id=&quot;username_field&quot;&gt;' : '&lt;div&gt;' ; ?&gt;
			&lt;label for=&quot;username&quot;&gt;Username&lt;span&gt;*&lt;/span&gt;:&lt;/label&gt;
			&lt;input name=&quot;username&quot; type=&quot;text&quot; id=&quot;username&quot; value=&quot;&lt;?php if (isset($get_my_fields['username'])) echo $get_my_fields['username']; ?&gt;&quot; /&gt;
		&lt;/div&gt;

		&lt;?php echo (isset($processed_form['issues']['password'])) ? '&lt;p&gt;'.$processed_form['issues']['password'].'&lt;/p&gt;&lt;div id=&quot;password_field&quot;&gt;' : '&lt;div&gt;' ; ?&gt;
			&lt;label for=&quot;password&quot;&gt;Password&lt;span&gt;*&lt;/span&gt;:&lt;/label&gt;
			&lt;input name=&quot;password&quot; type=&quot;password&quot; id=&quot;password&quot; /&gt;
		&lt;/div&gt;

		&lt;div&gt;
			&lt;label&gt; &amp;nbsp; &lt;/label&gt;
			&lt;input name=&quot;login&quot; type=&quot;submit&quot; id=&quot;login&quot; value=&quot;login&quot; /&gt;
		&lt;/div&gt;
	&lt;/form&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p><strong>backend.php</strong></p>
<pre class="brush: php;">
&lt;?php
//-----deschid sesiunea pentru a verifica daca utilizatorul s-a autentificat sau nu
#1
session_start();

//-----incarc include-urile care imi filtreaza URL-urile obtinute dinamic, http_user_agent-ul si cookie-urile
#2
include('includes/filter_it.inc.php');
include('includes/filtered_urls_and_cookies.inc.php');

//-----daca utilizatorul nu s-a autentificat va fi redirectionat catre pagina de login
#3
if (!isset($_SESSION['username']) || !isset($_SESSION['browser_os']) || $_SESSION['browser_os'] != sha1($browser_os)) {
		header('Location:http://'.$_SERVER['HTTP_HOST'].dirname($php_self).'/loginf.php');
		exit();
}

//-----scriptul care asigura functia de logout
#4
if (isset($_GET['action']) &amp;&amp; $_GET['action'] == 'logout') {
	//-----distrug toate variabilele sesiunii de pe server reinitializind intregul tablou superglobal $_SESSION
	#4.1
	$_SESSION = array();

	//-----sterg de pe server toate datele sesiunii apeland functia session_destroy() si sterg de pe PC-ul utilizatorului cookie-ul care stocheaza identificatorul de sesiune
	#4.2
	if (session_destroy() &amp;&amp; setcookie('PHPSESSID', '', time()-300, '/', '', 0)) {
		header('Location:http://'.$_SERVER['HTTP_HOST'].dirname($php_self).'/loginf.php');
		exit();
	}
}
?&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Backend&lt;/title&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot; /&gt;
&lt;meta name=&quot;description&quot; content=&quot;How do I make a backend?&quot; /&gt;
&lt;meta name=&quot;keywords&quot; content=&quot;backend,administration,section,admin,cms,content,managament,system,php,script,mysql,database&quot; /&gt;
&lt;meta name=&quot;abstract&quot; content=&quot;How do I make a backend?&quot; /&gt;
&lt;meta name=&quot;author&quot; content=&quot;AccesInterzis&quot; /&gt;
&lt;meta name=&quot;copyright&quot; content=&quot;AccesInterzis&quot; /&gt;
&lt;meta name=&quot;robots&quot; content=&quot;index,follow&quot; /&gt;
&lt;meta name=&quot;revisit-after&quot; content=&quot;7 days&quot; /&gt;

&lt;link href=&quot;http://www.accesinterzis.ro/myportofolio/css/reset.css&quot; type=&quot;text/css&quot; rel=&quot;stylesheet&quot; media=&quot;all&quot; /&gt;
&lt;style type=&quot;text/css&quot;&gt;
* {
	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 SECTIUNII DE ADMINISTRARE*/

div#backend {
	width:1000px;
	margin:10px auto;
	overflow:auto;
	border:1px #ccc solid;
	padding:10px;
}

div#backend a {
	color:#900;
	text-decoration:none;
}

div#backend ul#welcome_message {
	overflow:auto;
	list-style-type:none;
}

div#backend ul#sidebar {
	width:10%;
	float:left;
	list-style-type:none;
	border-right:1px #ccc solid;
}

div#backend div#mainarea {
	width:80%;
	float:right;
}

div#backend div#mainarea p#confirmation_message {
	width:75%;
	margin:250px auto;
}

div#backend div#footer{
	width:100%;
	float:left;
	text-align:center;
}

div.splitter {
	width:100%;
	height:1px;
	clear:both;
	float:left;
	border-top:1px #ccc solid;
	margin: 10px 0 10px 0;
}

/*SFARSIT - LINIILE CSS CARE CREEAZA SKINUL SECTIUNII DE ADMINISTRARE*/
&lt;/style&gt;
&lt;/head&gt;

&lt;body&gt;

&lt;div id=&quot;backend&quot;&gt;
	&lt;ul id=&quot;welcome_message&quot;&gt;
		&lt;li style=&quot;float:left;&quot;&gt;Welcome &lt;strong&gt;&lt;?php echo $_SESSION['username']; ?&gt;&lt;/strong&gt; to the administration section&lt;/li&gt;
		&lt;li style=&quot;float:right;&quot;&gt;&lt;a href=&quot;&lt;?php echo 'http://'.$_SERVER['HTTP_HOST'].$php_self; ?&gt;?action=logout&quot; title=&quot;Logout&quot;&gt;Logout&lt;/a&gt;&lt;/li&gt;
	&lt;/ul&gt;

	&lt;div class=&quot;splitter&quot;&gt;&lt;/div&gt;

	&lt;ul id=&quot;sidebar&quot;&gt;
		&lt;?php
		for ($i = 0; $i &lt; 40; $i++) {
			echo '&lt;li&gt;sidebar&lt;/li&gt;';
		}
		?&gt;
	&lt;/ul&gt;

	&lt;div id=&quot;mainarea&quot;&gt;
		&lt;p id=&quot;confirmation_message&quot;&gt;
		&lt;strong&gt;&lt;?php echo $_SESSION['username']; ?&gt;&lt;/strong&gt;, esti aici deoarece ai dovedit ca esti un utilizator autorizat al acestei sectiuni de administrare.
		Acum delogheaza-te si incearca sa accesezi din nou &lt;strong&gt;&lt;?php echo 'http://'.$_SERVER['HTTP_HOST'].$php_self; ?&gt;&lt;/strong&gt;.
		Vei vedea ce se intampla cand cineva neautentificat incearca sa intre in sectiunea de administrare.
		&lt;/p&gt;
	&lt;/div&gt;

	&lt;div class=&quot;splitter&quot;&gt;&lt;/div&gt;

	&lt;div id=&quot;footer&quot;&gt;
		Designed and developed by &lt;a href=&quot;http://www.accesinterzis.ro&quot; title=&quot;Programare | Web development | Web design | Securitate IT | SEO&quot; target=&quot;_blank&quot;&gt;www.accesinterzis.ro&lt;/a&gt; &amp;copy; 2010. All rights reserved.
	&lt;/div&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=Cum+fac+un+formular+de+autentificare+a+utilizatorilor%3F+%28versiunea+2%29+http://q423b.th8.us" title="Publica acest articol pe Twitter"><img class="nothumb" src="http://www.accesinterzis.ro/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=Cum+fac+un+formular+de+autentificare+a+utilizatorilor%3F+%28versiunea+2%29+http://q423b.th8.us" title="Publica acest articol pe Twitter">Publica acest articol pe Twitter</a></p>

<p><strong>Articole asemanatoare:<ul><li><a href='http://www.accesinterzis.ro/index.php/web/cum-fac-un-formular-de-inregistrare-a-utilizatorilor-versiunea-2/' rel='bookmark' title='Permanent Link: Cum fac un formular de inregistrare a utilizatorilor? (versiunea 2)'>Cum fac un formular de inregistrare a utilizatorilor? (versiunea 2)</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-autentificare-a-utilizatorilor/' rel='bookmark' title='Permanent Link: Cum fac un formular de autentificare a utilizatorilor?'>Cum fac un formular de autentificare a utilizatorilor?</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-contact-versiunea-2/' rel='bookmark' title='Permanent Link: Cum fac un formular de contact? (versiunea 2)'>Cum fac un formular de contact? (versiunea 2)</a></li>
</ul></p>]]></content:encoded>
			<wfw:commentRss>http://www.accesinterzis.ro/index.php/web/cum-fac-un-formular-de-autentificare-a-utilizatorilor-versiunea-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Cum fac un formular de inregistrare a utilizatorilor? (versiunea 2)</title>
		<link>http://www.accesinterzis.ro/index.php/web/cum-fac-un-formular-de-inregistrare-a-utilizatorilor-versiunea-2/</link>
		<comments>http://www.accesinterzis.ro/index.php/web/cum-fac-un-formular-de-inregistrare-a-utilizatorilor-versiunea-2/#comments</comments>
		<pubDate>Wed, 17 Mar 2010 13:41:46 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[web]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.accesinterzis.ro/?p=386</guid>
		<description><![CDATA[Scripturile PHP apelate prin functia include() le gasiti in articolul despre versiunea 2 a formularului de contact.
Interogarea SQL care creeaza tabelul in care se vor stoca utilizatorii o gasiti in articolul despre prima versiune a formularului de inregistrare a utilizatorilor.

registrationf.php

&#60;?php
/*
Cum fac un formular de inregistrare a utilizatorilor? (versiunea 2)
Autor: Marian Barbu aka AccesInterzis
Website: http://www.accesinterzis.ro
2010 (c) [...]


<strong>Articole asemanatoare:<ul><li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-inregistrare-a-utilizatorilor/' rel='bookmark' title='Permanent Link: Cum fac un formular de inregistrare a utilizatorilor?'>Cum fac un formular de inregistrare a utilizatorilor?</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/web/cum-fac-un-formular-de-autentificare-a-utilizatorilor-versiunea-2/' rel='bookmark' title='Permanent Link: Cum fac un formular de autentificare a utilizatorilor? (versiunea 2)'>Cum fac un formular de autentificare a utilizatorilor? (versiunea 2)</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-comentarii-versiunea-2/' rel='bookmark' title='Permanent Link: Cum fac un formular de comentarii? (versiunea 2)'>Cum fac un formular de comentarii? (versiunea 2)</a></li>
</ul>]]></description>
			<content:encoded><![CDATA[<p>Scripturile PHP apelate prin functia include() le gasiti in <a title="Cum fac un formular de contact? (versiunea 2)" href="http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-contact-versiunea-2/" target="_blank">articolul despre versiunea 2 a formularului de contact</a>.<br />
Interogarea SQL care creeaza tabelul in care se vor stoca utilizatorii o gasiti in <a title="Cum fac un formular de inregistrare a utilizatorilor?" href="http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-inregistrare-a-utilizatorilor/" target="_blank">articolul despre prima versiune a formularului de inregistrare a utilizatorilor</a>.</p>
<p><span id="more-386"></span></p>
<p><strong>registrationf.php</strong></p>
<pre class="brush: php;">
&lt;?php
/*
Cum fac un formular de inregistrare a utilizatorilor? (versiunea 2)
Autor: Marian Barbu aka AccesInterzis
Website: http://www.accesinterzis.ro
2010 (c) Toate drepturile rezervate
*/

//-----specific EXACT cu ce campuri se va lucra
#1
$required_fields = array('username', 'email', 'password', 'retype_password', 'register');
$sent_fields = array_keys($_POST);

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

//-----incarc fisierele include
#2.1
include('includes/validators.inc.php');
include('includes/filter_it.inc.php');
include('includes/validate_form.inc.php');
include('includes/filtered_urls_and_cookies.inc.php');

//------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
#3
if ($referer == 'http://'.$_SERVER['HTTP_HOST'].$php_self &amp;&amp; $required_fields == $sent_fields) {
	//-----procesez datele din formular; rezultatul va fi o lista de erori, o lista cu datele nevalide, o lista cu datele valide
	#5
	include('includes/process_form.inc.php');

	//-----infasor datele VALIDE in mysql_real_escape_string() deoarece urmeaza sa interoghez baza de date
	#6
	$processed_form['good_data'] = filter_it($processed_form['good_data'], array('mysql_real_escape_string'));

	//-----BEGIN - DATA HANDLING
	#7
	if (isset($processed_form['good_data']['username'])) {
		$q = &quot;SELECT user_id FROM ai_registrationform WHERE LOWER(username)='&quot;.strtolower($processed_form['good_data']['username']).&quot;'&quot;;
        $result = mysql_query($q) or die(mysql_error());

		if (mysql_num_rows($result) != 0) {
			$processed_form['issues']['username'] = 'The username &lt;strong&gt;'.$processed_form['good_data']['username'].'&lt;/strong&gt; already exists in our database.';
		}
	}

	if (isset($processed_form['good_data']['email'])) {
		$q = &quot;SELECT user_id FROM ai_registrationform WHERE LOWER(email)='&quot;.strtolower($processed_form['good_data']['email']).&quot;'&quot;;
        $result = mysql_query($q) or die(mysql_error());

        if (mysql_num_rows($result) != 0) {
			$processed_form['issues']['email'] = 'The email address &lt;strong&gt;'.$processed_form['good_data']['email'].'&lt;/strong&gt; already exists in our database.';
		}
	}

	if (isset($processed_form['good_data']['password'])) {
		if ($processed_form['good_data']['password'] != $_POST['retype_password']) {
			$processed_form['issues']['password'] = 'The two passwords don\'t match.';
		}
	}
	//-----END - DATA HANDLING

	//------daca nu exista niciun fel de erori bag datele in baza de date
    #8
	if(count($processed_form['issues']) == 0) {
		$q = &quot;INSERT INTO ai_registrationform(`username`, `email`, `password`, `registration_date`, `ip`)&quot;
			.&quot;VALUES('&quot;.$processed_form['good_data']['username'].&quot;', '&quot;.$processed_form['good_data']['email'].&quot;', SHA('&quot;.$processed_form['good_data']['password'].&quot;'), NOW(), '&quot;.$_SERVER['REMOTE_ADDR'].&quot;')&quot;;

		//-----daca intr-adevar datele au fost bagate in baza de date se va afisa pe monitor un mesaj de confirmare
		#8.1
		if (mysql_query($q)) {
			$confirmation = 'The user &lt;strong&gt;'.$processed_form['good_data']['username'].'&lt;/strong&gt; was succesfully registered in our databse.';
		} else {
			$confirmation = 'Something is wrong with the server. The user &lt;strong&gt;'.$processed_form['good_data']['username'].'&lt;/strong&gt; wasn\'t registered.';
		}

		$confirmation .= ' &lt;a href=&quot;http://'.$_SERVER['HTTP_HOST'].$php_self.'&quot; title=&quot;Back&quot; id=&quot;back&quot;&gt;Back to registration form&lt;/a&gt;';

		#8.2
		$display = 'style=&quot;display:none;&quot;';
	}

	//-----infasor datele in htmlentities() deoarece urmeaza sa le afisez in formular
	#9
	$get_my_fields = filter_it($get_my_fields, array('htmlentities'));
}
?&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;How do I make a registration form?&lt;/title&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot; /&gt;
&lt;meta name=&quot;description&quot; content=&quot;How do I make a registration form?&quot; /&gt;
&lt;meta name=&quot;keywords&quot; content=&quot;registration,form,php,script,mysql,database,user,backend,admin,section,cms&quot; /&gt;
&lt;meta name=&quot;abstract&quot; content=&quot;How do I make a registration form?&quot; /&gt;
&lt;meta name=&quot;author&quot; content=&quot;AccesInterzis&quot; /&gt;
&lt;meta name=&quot;copyright&quot; content=&quot;AccesInterzis&quot; /&gt;
&lt;meta name=&quot;robots&quot; content=&quot;index,follow&quot; /&gt;
&lt;meta name=&quot;revisit-after&quot; content=&quot;7 days&quot; /&gt;

&lt;style type=&quot;text/css&quot;&gt;
* {
	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 INREGISTRARE*/

div#registrationf {
	width:335px;
	margin:0px auto;
}

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

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

div#registrationf label {
	width:130px;
	float:left;
}

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

div#registrationf input {
	width:200px;
}

div#registrationf textarea {
	width:300px;
	height:150px;
}

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

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

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

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

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

div#registrationf div#username_field label,
div#registrationf div#email_field label,
div#registrationf div#password_field label,
div#registrationf div#retype_password_field label {
	color:#c00;
}

div#registrationf div#username_field input,
div#registrationf div#email_field input,
div#registrationf div#password_field input,
div#registrationf div#retype_password_field input {
	border:1px #c00 solid;
	color:#c00;
}

div#registrationf div#username_field input:hover,
div#registrationf div#email_field input:hover,
div#registrationf div#password_field input:hover,
div#registrationf div#retype_password_field input:hover {
	border:1px #c00 solid;
}
/*Sfarsit - stilurile erorilor*/

div#registrationf a#back {
	color:#900;
	font-weight:bold;
	text-decoration:underline;
}

/*SFARSIT - LINIILE CSS CARE CREEAZA SKINUL FORMULARULUI DE INREGISTRARE*/
&lt;/style&gt;
&lt;/head&gt;

&lt;body&gt;
&lt;div id=&quot;registrationf&quot;&gt;
	&lt;h1&gt;
		&lt;label&gt;&amp;nbsp;&lt;/label&gt;
		Register an user
	&lt;/h1&gt;

	&lt;?php if (isset($confirmation)) echo '&lt;p&gt;'.$confirmation.'&lt;/p&gt;'; ?&gt;

	&lt;form action=&quot;&lt;?php echo 'http://'.$_SERVER['HTTP_HOST'].$php_self; ?&gt;&quot; method=&quot;post&quot; &lt;?php if (isset($display)) echo $display; ?&gt;&gt;
		&lt;?php echo (isset($processed_form['issues']['username'])) ? '&lt;p&gt;'.$processed_form['issues']['username'].'&lt;/p&gt;&lt;div id=&quot;username_field&quot;&gt;' : '&lt;div&gt;' ; ?&gt;
			&lt;label for=&quot;username&quot;&gt;Username&lt;span&gt;*&lt;/span&gt;:&lt;/label&gt;
			&lt;input name=&quot;username&quot; type=&quot;text&quot; id=&quot;username&quot; value=&quot;&lt;?php if (isset($get_my_fields['username'])) echo $get_my_fields['username']; ?&gt;&quot; /&gt;
		&lt;/div&gt;

		&lt;?php echo (isset($processed_form['issues']['email'])) ? '&lt;p&gt;'.$processed_form['issues']['email'].'&lt;/p&gt;&lt;div id=&quot;email_field&quot;&gt;' : '&lt;div&gt;' ; ?&gt;
			&lt;label for=&quot;email&quot;&gt;Email&lt;span&gt;*&lt;/span&gt;:&lt;/label&gt;
			&lt;input name=&quot;email&quot; type=&quot;text&quot; id=&quot;email&quot; value=&quot;&lt;?php if (isset($get_my_fields['email'])) echo $get_my_fields['email']; ?&gt;&quot; /&gt;
		&lt;/div&gt;

		&lt;?php echo (isset($processed_form['issues']['password'])) ? '&lt;p&gt;'.$processed_form['issues']['password'].'&lt;/p&gt;&lt;div id=&quot;password_field&quot;&gt;' : '&lt;div&gt;' ; ?&gt;
			&lt;label for=&quot;password&quot;&gt;Password&lt;span&gt;*&lt;/span&gt;:&lt;/label&gt;
			&lt;input name=&quot;password&quot; type=&quot;password&quot; id=&quot;password&quot; /&gt;
		&lt;/div&gt;

		&lt;div&gt;
			&lt;label for=&quot;retype_password&quot;&gt;Retype password&lt;span&gt;*&lt;/span&gt;:&lt;/label&gt;
			&lt;input name=&quot;retype_password&quot; type=&quot;password&quot; id=&quot;retype_password&quot; /&gt;
		&lt;/div&gt;

		&lt;div&gt;
			&lt;label&gt; &amp;nbsp; &lt;/label&gt;
			&lt;input name=&quot;register&quot; type=&quot;submit&quot; id=&quot;register&quot; value=&quot;register&quot; /&gt;
		&lt;/div&gt;
	&lt;/form&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=Cum+fac+un+formular+de+inregistrare+a+utilizatorilor%3F+%28versiunea+2%29+http://gtspb.th8.us" title="Publica acest articol pe Twitter"><img class="nothumb" src="http://www.accesinterzis.ro/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=Cum+fac+un+formular+de+inregistrare+a+utilizatorilor%3F+%28versiunea+2%29+http://gtspb.th8.us" title="Publica acest articol pe Twitter">Publica acest articol pe Twitter</a></p>

<p><strong>Articole asemanatoare:<ul><li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-inregistrare-a-utilizatorilor/' rel='bookmark' title='Permanent Link: Cum fac un formular de inregistrare a utilizatorilor?'>Cum fac un formular de inregistrare a utilizatorilor?</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/web/cum-fac-un-formular-de-autentificare-a-utilizatorilor-versiunea-2/' rel='bookmark' title='Permanent Link: Cum fac un formular de autentificare a utilizatorilor? (versiunea 2)'>Cum fac un formular de autentificare a utilizatorilor? (versiunea 2)</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-comentarii-versiunea-2/' rel='bookmark' title='Permanent Link: Cum fac un formular de comentarii? (versiunea 2)'>Cum fac un formular de comentarii? (versiunea 2)</a></li>
</ul></p>]]></content:encoded>
			<wfw:commentRss>http://www.accesinterzis.ro/index.php/web/cum-fac-un-formular-de-inregistrare-a-utilizatorilor-versiunea-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cum fac un formular de comentarii? (versiunea 2)</title>
		<link>http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-comentarii-versiunea-2/</link>
		<comments>http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-comentarii-versiunea-2/#comments</comments>
		<pubDate>Wed, 17 Mar 2010 13:37:48 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[programare]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.accesinterzis.ro/?p=385</guid>
		<description><![CDATA[Scripturile PHP apelate prin functia include() le gasiti in articolul despre versiunea 2 a formularului de contact.
Interogarea SQL care creeaza tabelul in care se vor stoca comentariile o gasiti in articolul despre prima versiune a formularului de comentarii.

commentf.php

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

//-----specific [...]


<strong>Articole asemanatoare:<ul><li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-comentarii/' rel='bookmark' title='Permanent Link: Cum fac un formular de comentarii?'>Cum fac un formular de comentarii?</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-contact-versiunea-2/' rel='bookmark' title='Permanent Link: Cum fac un formular de contact? (versiunea 2)'>Cum fac un formular de contact? (versiunea 2)</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/web/cum-fac-un-formular-de-inregistrare-a-utilizatorilor-versiunea-2/' rel='bookmark' title='Permanent Link: Cum fac un formular de inregistrare a utilizatorilor? (versiunea 2)'>Cum fac un formular de inregistrare a utilizatorilor? (versiunea 2)</a></li>
</ul>]]></description>
			<content:encoded><![CDATA[<p>Scripturile PHP apelate prin functia include() le gasiti in <a title="Cum fac un formular de contact? (versiunea 2)" href="http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-contact-versiunea-2/" target="_blank">articolul despre versiunea 2 a formularului de contact</a>.<br />
Interogarea SQL care creeaza tabelul in care se vor stoca comentariile o gasiti in <a title="Cum fac un formular de comentarii?" href="http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-comentarii/" target="_blank">articolul despre prima versiune a formularului de comentarii</a>.</p>
<p><span id="more-385"></span></p>
<p><strong>commentf.php</strong></p>
<pre class="brush: php;">
&lt;?php
/*
Titlu: Cum fac un formular de comentarii? (versiunea 2)
Autor: Marian Barbu aka AccesInterzis
Website: http://www.accesinterzis.ro
2010 (c) Toate drepturile rezervate
*/

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

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

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

//-----incarc fisierele include
#3.1
include('includes/validators.inc.php');
include('includes/filter_it.inc.php');
include('includes/validate_form.inc.php');
include('includes/filtered_urls_and_cookies.inc.php');

//------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
#4
if ($referer == 'http://'.$_SERVER['HTTP_HOST'].$php_self &amp;&amp; $required_fields == $sent_fields) {
	//-----procesez datele din formular; rezultatul va fi o lista de erori, o lista cu datele nevalide, o lista cu datele valide
	#5
	include('includes/process_form.inc.php');

	//-----infasor datele in mysql_real_escape_string() deoarece urmeaza sa le bag in baza de date
	#6
	$processed_form['good_data'] = filter_it($processed_form['good_data'], array('mysql_real_escape_string'));

	//------daca nu exista niciun fel de erori bag datele in baza de date
    #7
	if(count($processed_form['issues']) == 0) {
		#7.1
		$q = &quot;INSERT INTO ai_commentform(`name`, `email`, `website`, `comment`, `date`, `ip`)&quot;
			.&quot;VALUES('&quot;.$processed_form['good_data']['name'].&quot;', '&quot;.$processed_form['good_data']['email'].&quot;', '&quot;.$processed_form['good_data']['website'].&quot;', '&quot;.$processed_form['good_data']['comment'].&quot;', NOW(), '&quot;.$_SERVER['REMOTE_ADDR'].&quot;')&quot;;

		#7.2
		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
	#8
	$get_my_fields = filter_it($get_my_fields, array('htmlentities'));
}
?&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;How do I make a comment form?&lt;/title&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot; /&gt;
&lt;meta name=&quot;description&quot; content=&quot;How do I make a comment form?&quot; /&gt;
&lt;meta name=&quot;keywords&quot; content=&quot;comment,form,php,script,add,email&quot; /&gt;
&lt;meta name=&quot;abstract&quot; content=&quot;How do I make a comment form?&quot; /&gt;
&lt;meta name=&quot;author&quot; content=&quot;AccesInterzis&quot; /&gt;
&lt;meta name=&quot;copyright&quot; content=&quot;AccesInterzis&quot; /&gt;
&lt;meta name=&quot;robots&quot; content=&quot;index,follow&quot; /&gt;
&lt;meta name=&quot;revisit-after&quot; content=&quot;7 days&quot; /&gt;

&lt;style type=&quot;text/css&quot;&gt;
* {
	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*/
&lt;/style&gt;
&lt;/head&gt;

&lt;body&gt;
&lt;?php
$q = &quot;SELECT name, website, date, comment FROM ai_commentform ORDER BY comment_id DESC&quot;;
$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 '&lt;div id=&quot;comments&quot;&gt;';
	echo '&lt;h1&gt;'.mysql_num_rows($result).' comment(s) so far&lt;/h1&gt;';

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

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

		$i++;
	}
	echo '&lt;/div&gt;';
}
?&gt;
&lt;div id=&quot;commentf&quot;&gt;
	&lt;h1&gt;
		&lt;label&gt;&amp;nbsp;&lt;/label&gt;
		Leave a comment
	&lt;/h1&gt;

	&lt;form action=&quot;&lt;?php echo 'http://'.$_SERVER['HTTP_HOST'].$php_self; ?&gt;&quot; method=&quot;post&quot; id=&quot;form-itself&quot;&gt;
		&lt;?php echo (isset($processed_form['issues']['name'])) ? '&lt;p&gt;'.$processed_form['issues']['name'].'&lt;/p&gt;&lt;div id=&quot;name_field&quot;&gt;' : '&lt;div&gt;' ; ?&gt;
			&lt;label for=&quot;name&quot;&gt;Name&lt;span&gt;*&lt;/span&gt;:&lt;/label&gt;
			&lt;input name=&quot;name&quot; type=&quot;text&quot; id=&quot;name&quot; value=&quot;&lt;?php if (isset($get_my_fields['name'])) echo $get_my_fields['name']; ?&gt;&quot; /&gt;
		&lt;/div&gt;

		&lt;?php echo (isset($processed_form['issues']['email'])) ? '&lt;p&gt;'.$processed_form['issues']['email'].'&lt;/p&gt;&lt;div id=&quot;email_field&quot;&gt;' : '&lt;div&gt;' ; ?&gt;
			&lt;label for=&quot;email&quot;&gt;Email&lt;span&gt;*&lt;/span&gt;:&lt;/label&gt;
			&lt;input name=&quot;email&quot; type=&quot;text&quot; id=&quot;email&quot; value=&quot;&lt;?php if (isset($get_my_fields['email'])) echo $get_my_fields['email']; ?&gt;&quot; /&gt;
		&lt;/div&gt;

		&lt;?php echo (isset($processed_form['issues']['website'])) ? '&lt;p&gt;'.$processed_form['issues']['website'].'&lt;/p&gt;&lt;div id=&quot;website_field&quot;&gt;' : '&lt;div&gt;' ; ?&gt;
			&lt;label for=&quot;website&quot;&gt;Website:&lt;/label&gt;
			&lt;input name=&quot;website&quot; type=&quot;text&quot; id=&quot;website&quot; value=&quot;&lt;?php if (isset($get_my_fields['website'])) echo $get_my_fields['website']; ?&gt;&quot; /&gt;
		&lt;/div&gt;

		&lt;?php echo (isset($processed_form['issues']['comment'])) ? '&lt;p&gt;'.$processed_form['issues']['comment'].'&lt;/p&gt;&lt;div id=&quot;comment_field&quot;&gt;' : '&lt;div&gt;' ; ?&gt;
			&lt;label for=&quot;comment&quot;&gt;Your comment&lt;span&gt;*&lt;/span&gt;:&lt;/label&gt;
			&lt;textarea name=&quot;comment&quot; rows=&quot;1&quot; cols=&quot;1&quot; id=&quot;comment&quot;&gt;&lt;?php if (isset($get_my_fields['comment'])) echo $get_my_fields['comment']; ?&gt;&lt;/textarea&gt;
		&lt;/div&gt;

		&lt;p&gt;
			&lt;img src=&quot;includes/captchaimage.inc.php?width=120&amp;height=40&amp;characters=5&quot; /&gt;
		&lt;p&gt;

		&lt;?php echo (isset($processed_form['issues']['security_code'])) ? '&lt;p&gt;'.$processed_form['issues']['security_code'].'&lt;/p&gt;&lt;div id=&quot;security_code_field&quot;&gt;' : '&lt;div&gt;' ; ?&gt;
			&lt;label for=&quot;security_code&quot;&gt;Are you human?&lt;span&gt;*&lt;/span&gt;&lt;/label&gt;
			&lt;input id=&quot;security_code&quot; name=&quot;security_code&quot; type=&quot;text&quot; /&gt;
		&lt;/div&gt;

		&lt;div&gt;
			&lt;label&gt; &amp;nbsp; &lt;/label&gt;
			&lt;input name=&quot;add&quot; type=&quot;submit&quot; id=&quot;add&quot; value=&quot;add&quot; /&gt;
		&lt;/div&gt;
	&lt;/form&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=Cum+fac+un+formular+de+comentarii%3F+%28versiunea+2%29+http://5ot2h.th8.us" title="Publica acest articol pe Twitter"><img class="nothumb" src="http://www.accesinterzis.ro/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=Cum+fac+un+formular+de+comentarii%3F+%28versiunea+2%29+http://5ot2h.th8.us" title="Publica acest articol pe Twitter">Publica acest articol pe Twitter</a></p>

<p><strong>Articole asemanatoare:<ul><li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-comentarii/' rel='bookmark' title='Permanent Link: Cum fac un formular de comentarii?'>Cum fac un formular de comentarii?</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-contact-versiunea-2/' rel='bookmark' title='Permanent Link: Cum fac un formular de contact? (versiunea 2)'>Cum fac un formular de contact? (versiunea 2)</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/web/cum-fac-un-formular-de-inregistrare-a-utilizatorilor-versiunea-2/' rel='bookmark' title='Permanent Link: Cum fac un formular de inregistrare a utilizatorilor? (versiunea 2)'>Cum fac un formular de inregistrare a utilizatorilor? (versiunea 2)</a></li>
</ul></p>]]></content:encoded>
			<wfw:commentRss>http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-comentarii-versiunea-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cum fac un formular de contact? (versiunea 2)</title>
		<link>http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-contact-versiunea-2/</link>
		<comments>http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-contact-versiunea-2/#comments</comments>
		<pubDate>Wed, 17 Mar 2010 13:15:27 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[programare]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.accesinterzis.ro/?p=380</guid>
		<description><![CDATA[Ce am facut nou rescriind acest formular de contact? Pai&#8230;am reusit sa scriem cod procedural reutilizabil. Daca dorim sa devenim programatori PHP trebuie sa ne axam foarte, foarte, foarte mult (am omis cumva sa zic &#8220;foarte mult&#8221;?) pe acest concept de cod procedural reutilizabil. N-ar strica daca ar deveni un reflex in gandirea noastra atunci [...]


<strong>Articole asemanatoare:<ul><li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-comentarii-versiunea-2/' rel='bookmark' title='Permanent Link: Cum fac un formular de comentarii? (versiunea 2)'>Cum fac un formular de comentarii? (versiunea 2)</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/web/cum-fac-un-formular-de-inregistrare-a-utilizatorilor-versiunea-2/' rel='bookmark' title='Permanent Link: Cum fac un formular de inregistrare a utilizatorilor? (versiunea 2)'>Cum fac un formular de inregistrare a utilizatorilor? (versiunea 2)</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-contact/' rel='bookmark' title='Permanent Link: Cum fac un formular de contact?'>Cum fac un formular de contact?</a></li>
</ul>]]></description>
			<content:encoded><![CDATA[<p>Ce am facut nou rescriind <a title="Cum fac un formular de contact?" href="http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-contact/" target="_blank">acest formular de contact</a>? Pai&#8230;am reusit sa scriem <strong>cod procedural reutilizabil</strong>. Daca dorim sa devenim programatori PHP trebuie sa ne axam foarte, foarte, foarte mult (am omis cumva sa zic &#8220;foarte mult&#8221;?) pe acest concept de <strong>cod procedural reutilizabil</strong>. N-ar strica daca ar deveni un reflex in gandirea noastra atunci cand concepem un cod.</p>
<p><span id="more-380"></span></p>
<p><strong>contactf.php</strong></p>
<pre class="brush: php;">
&lt;?php
/*
Titlu: Cum fac un formular de contact? (versiunea 2)
Autor: Marian Barbu aka AccesInterzis
Website: http://www.accesinterzis.ro
2010 (c) Toate drepturile rezervate
*/

//-----specific EXACT cu ce campuri se va lucra
#1
$required_fields = array('name', 'phone_number', 'email', 'message', 'security_code', 'send');
$sent_fields = array_keys($_POST);

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

//-----incarc fisierele include
#3
include('includes/validators.inc.php');
include('includes/filter_it.inc.php');
include('includes/validate_form.inc.php');
include('includes/filtered_urls_and_cookies.inc.php');

//------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
#4
if ($referer == 'http://'.$_SERVER['HTTP_HOST'].$php_self &amp;&amp; $required_fields == $sent_fields) {
	//-----procesez datele din formular; rezultatul va fi o lista de erori, o lista cu datele nevalide, o lista cu datele valide
	#5
	include('includes/process_form.inc.php');

    //------daca nu exista niciun fel de erori trimit emailul
    #6
	if(count($processed_form['issues']) == 0) {
		//-----infasor datele in htmlentities() si nl2br() deoarece urmeaza sa le trimit
		#6.1
		$processed_form['good_data'] = filter_it($processed_form['good_data'], array('htmlentities','nl2br'));

        #6.2
        $to      = 'whovisitedme@gmail.com';
        $subject = substr($processed_form['good_data']['message'], 0, 20).'...';
        $body    = 'This message is received from http://'.$_SERVER['HTTP_HOST'].$php_self.'&lt;br /&gt;&lt;br /&gt;
                    &lt;strong&gt;Name&lt;/strong&gt;: '.$processed_form['good_data']['name'].'&lt;br /&gt;
                    &lt;strong&gt;Phone number&lt;/strong&gt;: '.$processed_form['good_data']['phone_number'].'&lt;br /&gt;
                    &lt;strong&gt;Email address&lt;/strong&gt;: '.$processed_form['good_data']['email'].'&lt;br /&gt;
                    &lt;strong&gt;Mesagge&lt;/strong&gt;: '.$processed_form['good_data']['message'].'&lt;br /&gt;&lt;br /&gt;
                    &lt;strong style=&quot;color:#c00;&quot;&gt;Infos about sender:&lt;/strong&gt;&lt;br /&gt;
                    &lt;strong&gt;IP address&lt;/strong&gt;: '.$_SERVER['REMOTE_ADDR'].'&lt;br /&gt;
                    &lt;strong&gt;browser and operating system&lt;/strong&gt;: '.$browser_os.'&lt;br /&gt;
                    &lt;strong&gt;dispatch hour&lt;/strong&gt;: '.date(&quot;l, F j, Y, H:i:s&quot;);
        $headers  = &quot;From: &quot;.$processed_form['good_data']['email'].&quot;\r\n&quot;;

        //-----ma asigur ca pot formata emailul cu taguri HTML si reguli CSS aplicate inline
		#6.3
        $headers .= 'MIME-Version: 1.0'.&quot;\r\n&quot;;
        $headers .= 'Content-type: text/html; charset=utf-8' . &quot;\r\n&quot;;

		//------daca emailul a fost intr-adevar trimis se va afisa pe monitor un mesaj de confirmare
        #6.4
        if (mail($to, $subject, $body, $headers)) {
			$confirmation = 'Your message was succesfully sent. We will get in touch with you as soon as possible.';
        } else {
			$confirmation = 'Something is wrong with the server. Your message wasn\'t sent.';
        }

		$confirmation .= ' &lt;a href=&quot;http://'.$_SERVER['HTTP_HOST'].$php_self.'&quot; title=&quot;Back&quot; id=&quot;back&quot;&gt;Back to contact form&lt;/a&gt;';

		#6.5
		$display = 'style=&quot;display:none;&quot;';
    }

	//-----infasor datele in htmlentities() deoarece urmeaza sa le afisez in formular
	#7
	$get_my_fields = filter_it($get_my_fields, array('htmlentities'));
}
?&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;How do I make a contact form?&lt;/title&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot; /&gt;
&lt;meta name=&quot;description&quot; content=&quot;How do I make a contact form?&quot; /&gt;
&lt;meta name=&quot;keywords&quot; content=&quot;contact,form,php,script,send,email&quot; /&gt;
&lt;meta name=&quot;abstract&quot; content=&quot;How do I make a contact form?&quot; /&gt;
&lt;meta name=&quot;author&quot; content=&quot;AccesInterzis&quot; /&gt;
&lt;meta name=&quot;copyright&quot; content=&quot;AccesInterzis&quot; /&gt;
&lt;meta name=&quot;robots&quot; content=&quot;index,follow&quot; /&gt;
&lt;meta name=&quot;revisit-after&quot; content=&quot;7 days&quot; /&gt;

&lt;style type=&quot;text/css&quot;&gt;
* {
	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#contactf {
	width:530px;
	margin:0px auto;
}

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

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

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

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

div#contactf input {
	width:200px;
}

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

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

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

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

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

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

div#contactf div#name_field label,
div#contactf div#email_field label,
div#contactf div#phone_number_field label,
div#contactf div#message_field label,
div#contactf div#security_code_field label {
	color:#c00;
}

div#contactf div#name_field input,
div#contactf div#email_field input,
div#contactf div#phone_number_field input,
div#contactf div#message_field textarea,
div#contactf div#security_code_field input {
	border:1px #c00 solid;
	color:#c00;
}

div#contactf div#name_field input:hover,
div#contactf div#email_field input:hover,
div#contactf div#phone_number_field input:hover,
div#contactf div#message_field textarea:hover,
div#contactf div#security_code_field input:hover {
	border:1px #c00 solid;
}

div#contactf a#back {
	color:#900;
	font-weight:bold;
	text-decoration:underline;
}
/*Sfarsit - stilurile erorilor*/

/*SFARSIT - LINIILE CSS CARE CREEAZA SKINUL FORMULARULUI DE CONTACT*/
&lt;/style&gt;
&lt;/head&gt;

&lt;body&gt;
&lt;div id=&quot;contactf&quot;&gt;
	&lt;h1&gt;
        &lt;label&gt;&amp;nbsp;&lt;/label&gt;
        Contact us
    &lt;/h1&gt;

    &lt;?php if (isset($confirmation)) echo '&lt;p&gt;'.$confirmation.'&lt;/p&gt;'; ?&gt;

	&lt;form action=&quot;&lt;?php echo 'http://'.$_SERVER['HTTP_HOST'].$php_self; ?&gt;&quot; method=&quot;post&quot; &lt;?php if (isset($display)) echo $display; ?&gt;&gt;
		&lt;?php echo (isset($processed_form['issues']['name'])) ? '&lt;p&gt;'.$processed_form['issues']['name'].'&lt;/p&gt;&lt;div id=&quot;name_field&quot;&gt;' : '&lt;div&gt;' ; ?&gt;
			&lt;label for=&quot;name&quot;&gt;Name&lt;span&gt;*&lt;/span&gt;:&lt;/label&gt;
			&lt;input name=&quot;name&quot; type=&quot;text&quot; id=&quot;name&quot; value=&quot;&lt;?php if (isset($get_my_fields['name'])) echo $get_my_fields['name']; ?&gt;&quot; /&gt;
		&lt;/div&gt;

		&lt;?php echo (isset($processed_form['issues']['phone_number'])) ? '&lt;p&gt;'.$processed_form['issues']['phone_number'].'&lt;/p&gt;&lt;div id=&quot;phone_number_field&quot;&gt;' : '&lt;div&gt;' ; ?&gt;
			&lt;label for=&quot;phone_number&quot;&gt;Phone number&lt;span&gt;*&lt;/span&gt;:&lt;/label&gt;
			&lt;input name=&quot;phone_number&quot; type=&quot;text&quot; id=&quot;phone_number&quot; value=&quot;&lt;?php if (isset($get_my_fields['phone_number'])) echo $get_my_fields['phone_number']; ?&gt;&quot; /&gt;
		&lt;/div&gt;

		&lt;?php echo (isset($processed_form['issues']['email'])) ? '&lt;p&gt;'.$processed_form['issues']['email'].'&lt;/p&gt;&lt;div id=&quot;email_field&quot;&gt;' : '&lt;div&gt;' ; ?&gt;
			&lt;label for=&quot;email&quot;&gt;Email&lt;span&gt;*&lt;/span&gt;:&lt;/label&gt;
			&lt;input name=&quot;email&quot; type=&quot;text&quot; id=&quot;email&quot; value=&quot;&lt;?php if (isset($get_my_fields['email'])) echo $get_my_fields['email']; ?&gt;&quot; /&gt;
		&lt;/div&gt;

		&lt;?php echo (isset($processed_form['issues']['message'])) ? '&lt;p&gt;'.$processed_form['issues']['message'].'&lt;/p&gt;&lt;div id=&quot;message_field&quot;&gt;' : '&lt;div&gt;' ; ?&gt;
			&lt;label for=&quot;message&quot;&gt;Your message&lt;span&gt;*&lt;/span&gt;:&lt;/label&gt;
			&lt;textarea name=&quot;message&quot; rows=&quot;1&quot; cols=&quot;1&quot; id=&quot;message&quot;&gt;&lt;?php if (isset($get_my_fields['message'])) echo $get_my_fields['message']; ?&gt;&lt;/textarea&gt;
		&lt;/div&gt;

		&lt;p&gt;
			&lt;img src=&quot;includes/captchaimage.inc.php?width=120&amp;height=40&amp;characters=5&quot; /&gt;
		&lt;/p&gt;

		&lt;?php echo (isset($processed_form['issues']['security_code'])) ? '&lt;p&gt;'.$processed_form['issues']['security_code'].'&lt;/p&gt;&lt;div id=&quot;security_code_field&quot;&gt;' : '&lt;div&gt;' ; ?&gt;
			&lt;label for=&quot;security_code&quot;&gt;Are you human?&lt;span&gt;*&lt;/span&gt;&lt;/label&gt;
			&lt;input id=&quot;security_code&quot; name=&quot;security_code&quot; type=&quot;text&quot; /&gt;
		&lt;/div&gt;

		&lt;div&gt;
			&lt;label&gt; &amp;nbsp; &lt;/label&gt;
			&lt;input name=&quot;send&quot; type=&quot;submit&quot; id=&quot;send&quot; value=&quot;send&quot; /&gt;
		&lt;/div&gt;
	&lt;/form&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p><strong>validators.inc.php</strong></p>
<pre class="brush: php;">
&lt;?php
//----------lista de validatori pentru campurile tuturor formularelor
$validators = array('name'          =&gt; array('required'  =&gt; true,
											 'min_chars' =&gt; 3,
											 'max_chars' =&gt; 30,
											 'regex'     =&gt; '/^[a-z0-9][a-z0-9_ ]*[a-z0-9]$/i'),

					'phone_number'  =&gt; array('required'  =&gt; true,
											 'min_chars' =&gt; 3,
											 'max_chars' =&gt; 30,
											 'regex'     =&gt; '/^[0-9+][0-9. ]*[0-9]$/'),

					'email'         =&gt; array('required'  =&gt; true,
											 'min_chars' =&gt; 3,
											 'max_chars' =&gt; 30,
											 'regex'     =&gt; '/^[a-z0-9][a-z0-9_.]+@[a-z0-9-.]+\.[a-z]{2,4}$/i'),

					'website'       =&gt; array('required'  =&gt; false,
											 'min_chars' =&gt; 3,
											 'max_chars' =&gt; 30,
											 'regex'     =&gt; '/^http:\/\/[a-z0-9.-]+\.[a-z]{2,4}$/i'),

					'comment'       =&gt; array('required'  =&gt; true,
											 'min_chars' =&gt; 3,
											 'max_chars' =&gt; 20000,
											 'regex'     =&gt; '/.*/i'),

					'message'       =&gt; array('required'  =&gt; true,
											 'min_chars' =&gt; 3,
											 'max_chars' =&gt; 20000,
											 'regex'     =&gt; '/.*/i'),

					'username'      =&gt; array('required'  =&gt; true,
											 'min_chars' =&gt; 3,
											 'max_chars' =&gt; 30,
											 'regex'     =&gt; '/^[a-z0-9][a-z0-9_ ]*[a-z0-9]$/i'),

					'password'      =&gt; array('required'  =&gt; true,
											 'min_chars' =&gt; 5,
											 'max_chars' =&gt; 30,
											 'regex'     =&gt; '/^[a-z0-9]*$/i'),

					'security_code' =&gt; array('required'  =&gt; true,
											 'min_chars' =&gt; 3,
											 'max_chars' =&gt; 10,
											 'regex'     =&gt; '/^[a-z0-9]*$/i'));

?&gt;
</pre>
<p><strong>filter_it.inc.php</strong></p>
<pre class="brush: php;">
&lt;?php
function filter_it($unfiltered_data, $filters) {
	$wrapped_data = array();

	foreach ($unfiltered_data as $k =&gt; $v) {
		foreach ($filters as $filter) {
			switch ($filter) {
				case 'htmlentities':
					$v = htmlentities($v, ENT_QUOTES, 'utf-8');
					break;

				default:
					$v = $filter($v);
			}
		}

		$wrapped_data[$k] = $v;
	}

	return ($wrapped_data);
}
?&gt;
</pre>
<p><strong>validate_form.inc.php</strong></p>
<pre class="brush: php;">
&lt;?php
//----------functia care valideaza datele introduse de utilizator
function validate_form ($unverified_form, $validators) {
	include('includes/replacers.inc.php');
	$issues = array();
	$bad_data = array();

	foreach ($unverified_form as $k =&gt; $v) {
		if (empty($unverified_form[$k])) {
			if ($validators[$k]['required'] == true) {
				$issues[$k] = 'You forgot to enter the &lt;strong&gt;'.$replacers[$k].'&lt;/strong&gt;.';
				$bad_data[$k] = $unverified_form[$k];
			}
		} else {
			if (strlen($unverified_form[$k]) &lt; $validators[$k]['min_chars']) {
				$issues[$k] = 'The &lt;strong&gt;'.$replacers[$k].'&lt;/strong&gt; is too short.';
				$bad_data[$k] = $unverified_form[$k];
			} else {
				if (strlen($unverified_form[$k]) &gt; $validators[$k]['max_chars']) {
					$issues[$k] = 'The &lt;strong&gt;'.$replacers[$k].'&lt;/strong&gt; is too long.';
					$bad_data[$k] = $unverified_form[$k];
				} else {
					if (!preg_match($validators[$k]['regex'], $unverified_form[$k])) {
						$issues[$k] = 'The &lt;strong&gt;'.$replacers[$k].'&lt;/strong&gt; isn\'t valid.';
						$bad_data[$k] = $unverified_form[$k];
					}
				}
			}
		}
	}

	$good_data = array_diff_key($unverified_form, $bad_data);

	$result = array('issues' =&gt; $issues, 'bad_data' =&gt; $bad_data, 'good_data' =&gt; $good_data);

	return ($result);
}
?&gt;
</pre>
<p><strong>replacers.inc.php</strong></p>
<pre class="brush: php;">
&lt;?php
//----------lista cuvintelor care inlocuiesc cheile array-ul in mesajele de eroare
$replacers = array('name'          =&gt; 'name',
				   'phone_number'  =&gt; 'phone number',
				   'email'         =&gt; 'email address',
				   'website'       =&gt; 'website URL',
				   'comment'       =&gt; 'comment',
				   'message'       =&gt; 'message',
				   'username'      =&gt; 'username',
				   'password'      =&gt; 'password',
				   'security_code' =&gt; 'security code');
?&gt;
</pre>
<p><strong>filtered_urls_and_cookies.inc.php</strong></p>
<pre class="brush: php;">
&lt;?php
//-----infasor in strip_tags() si htmlentities() URL-urile obtinute dinamic, http_user_agent-ul si cookie-urile ca sa ma asigur ca nu contin cod malitios
$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;
$browser_os = htmlentities(strip_tags($_SERVER['HTTP_USER_AGENT']), ENT_QUOTES, 'utf-8');
$cookie = (isset($_COOKIE)) ? filter_it($_COOKIE, array('strip_tags', 'htmlentities')) : NULL;
?&gt;
</pre>
<p><strong>process_form.inc.php</strong></p>
<pre class="brush: php;">
&lt;?php
//-----incarc din lista generala de validatori validatorii pentru campurile formularului meu
$get_my_fields = array_intersect_key($_POST, $validators);
//-----infasor datele in trim() si stripslashes() deoarece urmeaza sa incep procesul de validare
$get_my_fields = filter_it($get_my_fields, array('trim', 'stripslashes'));
//-----rezultatul procesului de validare va fi o lista de erori, o lista cu datele nevalide, o lista cu datele valide
$processed_form = validate_form($get_my_fields, $validators);
?&gt;
</pre>
<p>Am reusit sa aduc codul la acest nivel datorita lui <a title="OriginalCopy" href="http://originalcopy-on.blogspot.com/" target="_blank">OriginalCopy</a>. Chiar daca el ar fi dorit sa arate muuuult mai compact. Dar el e un programator foarte bun, de multi ani in aceasta meserie, iar eu sunt doar un anonim care a inceput sa cocheteze cu aceste limbaje de programare web acum circa 2 ani in urma.</p>
<p>Sper ca la versiunea 3 a formularului sa implementez validare client-side cu jQuery, sa adaug un camp in care utilizatorul poate atasa si un fisier la email si sa rescriu codul PHP de asa natura incat sa fie mai compact si mai aproape de conceptul de <strong>cod procedural reutilizabil</strong>.</p>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=Cum+fac+un+formular+de+contact%3F+%28versiunea+2%29+http://fidgg.th8.us" title="Publica acest articol pe Twitter"><img class="nothumb" src="http://www.accesinterzis.ro/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=Cum+fac+un+formular+de+contact%3F+%28versiunea+2%29+http://fidgg.th8.us" title="Publica acest articol pe Twitter">Publica acest articol pe Twitter</a></p>

<p><strong>Articole asemanatoare:<ul><li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-comentarii-versiunea-2/' rel='bookmark' title='Permanent Link: Cum fac un formular de comentarii? (versiunea 2)'>Cum fac un formular de comentarii? (versiunea 2)</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/web/cum-fac-un-formular-de-inregistrare-a-utilizatorilor-versiunea-2/' rel='bookmark' title='Permanent Link: Cum fac un formular de inregistrare a utilizatorilor? (versiunea 2)'>Cum fac un formular de inregistrare a utilizatorilor? (versiunea 2)</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-contact/' rel='bookmark' title='Permanent Link: Cum fac un formular de contact?'>Cum fac un formular de contact?</a></li>
</ul></p>]]></content:encoded>
			<wfw:commentRss>http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-contact-versiunea-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cum fac un meniu de navigare in PHP, CSS, HTML?</title>
		<link>http://www.accesinterzis.ro/index.php/programare/cum-fac-un-meniu-de-navigare-in-php-css-html/</link>
		<comments>http://www.accesinterzis.ro/index.php/programare/cum-fac-un-meniu-de-navigare-in-php-css-html/#comments</comments>
		<pubDate>Sat, 13 Mar 2010 16:52:53 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[programare]]></category>
		<category><![CDATA[web design]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.accesinterzis.ro/?p=378</guid>
		<description><![CDATA[Nu o sa zic nimic despre acest meniu de navigare in interiorul unui site decat ca designul este realizat de Dr. Freak iar programarea PHP si redactarea HTML/CSS de mine. Enjoy studying the code!  
index.php, about.php, gallery.php, offerts.php, hotels.php, contact.php

&#60;?php
$php_self = htmlentities(strip_tags($_SERVER['PHP_SELF']), ENT_QUOTES, 'utf-8');
?&#62;
&#60;!DOCTYPE html PUBLIC &#34;-//W3C//DTD XHTML 1.0 Transitional//EN&#34; &#34;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&#34;&#62;
&#60;html xmlns=&#34;http://www.w3.org/1999/xhtml&#34;&#62;
&#60;head&#62;
&#60;title&#62;Travel agency&#60;/title&#62;
&#60;meta http-equiv=&#34;Content-Type&#34; [...]


<strong>Articole asemanatoare:<ul><li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-comentarii-versiunea-2/' rel='bookmark' title='Permanent Link: Cum fac un formular de comentarii? (versiunea 2)'>Cum fac un formular de comentarii? (versiunea 2)</a></li>
</ul>]]></description>
			<content:encoded><![CDATA[<p>Nu o sa zic nimic despre acest <a title="Cum fac un meniu de navigare in PHP, CSS, HTML?" href="http://accesinterzis.ro/myportofolio/nav-menu/index.php" target="_blank">meniu de navigare</a> in interiorul unui site decat ca designul este realizat de <a title="Dr. Freak" href="http://freakdr.deviantart.com" target="_blank">Dr. Freak</a> iar programarea PHP si redactarea HTML/CSS de mine. Enjoy studying the code! <img src='http://www.accesinterzis.ro/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p><strong>index.php, about.php, gallery.php, offerts.php, hotels.php, contact.php</strong></p>
<pre class="brush: php;">
&lt;?php
$php_self = htmlentities(strip_tags($_SERVER['PHP_SELF']), ENT_QUOTES, 'utf-8');
?&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
&lt;head&gt;
&lt;title&gt;Travel agency&lt;/title&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot; /&gt;
&lt;meta name=&quot;description&quot; content=&quot;Travel agency&quot; /&gt;
&lt;meta name=&quot;keywords&quot; content=&quot;travel,agency&quot; /&gt;
&lt;meta name=&quot;abstract&quot; content=&quot;Travel agency&quot; /&gt;
&lt;meta name=&quot;author&quot; content=&quot;AccesInterzis&quot; /&gt;
&lt;meta name=&quot;copyright&quot; content=&quot;AccesInterzis&quot; /&gt;
&lt;meta name=&quot;robots&quot; content=&quot;noindex,nofollow&quot; /&gt;
&lt;meta name=&quot;revisit-after&quot; content=&quot;7 days&quot; /&gt;

&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;css/nav-menu.css.php&quot; media=&quot;screen&quot; /&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;js/load-images.js.php&quot;&gt;&lt;/script&gt;
&lt;/head&gt;

&lt;body onload=&quot;download_images()&quot;&gt;
&lt;?php include('includes/nav-menu.inc.php'); ?&gt;

&lt;p id=&quot;content&quot;&gt;
&lt;?php echo basename($php_self).' page is under construction.'; ?&gt;
&lt;/p&gt;

&lt;?php include('includes/footer.inc.php'); ?&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p><span id="more-378"></span></p>
<p><strong>nav-menu.inc.php</strong></p>
<pre class="brush: php;">
&lt;ul id=&quot;nav_menu&quot;&gt;
	&lt;?php
	$nav_menu = array('home'    =&gt; 'index.php',
					  'about'   =&gt; 'about.php',
					  'gallery' =&gt; 'gallery.php',
					  'offerts' =&gt; 'offerts.php',
					  'hotels'  =&gt; 'hotels.php',
					  'contact' =&gt; 'contact.php');

	foreach ($nav_menu as $k =&gt; $v) {
		echo '&lt;li id=&quot;'.$k.'-item&quot;&gt;';
		echo '&lt;a href=&quot;'.$v.'&quot; title=&quot;'.ucfirst($k).'&quot; id=&quot;'.$k.'-btn&quot;';
		echo (basename($php_self) == $v) ? ' style=&quot;background:url(\'images/'.$k.'-hover.png\') no-repeat 0 0&quot;&gt;' : '&gt;';
		echo '&lt;span&gt;'.ucfirst($k).'&lt;/span&gt;';
		echo '&lt;/a&gt;';
		echo '&lt;/li&gt;';
	}
	?&gt;
&lt;/ul&gt;
</pre>
<p><strong>nav-menu.css.php</strong></p>
<pre class="brush: css;">
&lt;?php
header(&quot;Content-type: text/css; charset=utf-8&quot;);
?&gt;
* {
	margin:0;
	padding:0;
	outline:none;
}

html {
	color:black;
	background:#00c3ff url('../images/content-repeat-x.jpg') repeat-x 0 0;
	/*background-color background-image background-repeat background-attachment background-position*/
	font: normal normal normal 12px  Verdana;
	/*font-style font-variant font-weight font-size font-family*/
}

body {
	/*
	E important ca body sa nu aiba nicio culoare de fundal deoarece daca ar avea
	nu s-ar mai vedea repeat-x-ul de pe fundalul html-ului.
	*/
	background:url('../images/header-travel-agency.jpg') no-repeat top;
	height:567px;
}

/***********begin - navigation menu***********/

ul#nav_menu {
	width:816px;
	margin:0 auto;
	list-style-type:none;
	overflow:hidden;
	padding-top:360px;
}

ul#nav_menu li {
	float:left;
	margin-right:30px;
}

ul#nav_menu li#contact-item {
	margin-right:0;
}

ul#nav_menu a {
	display:block;
	width:111px;
	height:56px;
}

ul#nav_menu li a span {
	display:none;
}

&lt;?php
$btns = array('home', 'about', 'gallery', 'offerts', 'hotels', 'contact');

foreach ($btns as $item) {
	echo 'ul#nav_menu a#'.$item.'-btn {
		background:url(\'../images/'.$item.'.png\') no-repeat 0 0;
	}

	ul#nav_menu a#'.$item.'-btn:hover {
		background:url(\'../images/'.$item.'-hover.png\') no-repeat 0 0;
	}';
}
?&gt;

/***********end - navigation menu***********/

p#content {
	color:white;
	text-align:center;
	font-size:32px;
	margin-top:150px;
}

p#footer {
	width:100%;
	position:absolute;
	bottom:5px;
	text-align:center;
	font-size:10px;
}

p#footer  a {
	color:white;
	text-decoration:none;
}

p#footer  a:hover {
	text-decoration:underline;
}
</pre>
<p><strong>load-images.js.php</strong></p>
<pre class="brush: php;">
&lt;?php
header(&quot;content-type: application/x-javascript&quot;);

function load_images($folder) {
	$result = 'objImage = new Image();'.&quot;\r\n&quot;;

	$result .= 'function download_images(){'.&quot;\r\n&quot;;
	$allowed_extensions = array ('.jpg', '.jpeg', '.png', '.gif');
	$open = opendir ($folder);	

	$i = 0;
	while ($filename = readdir($open)) {
		if ($filename != '.' &amp;&amp; $filename != '..') {
			$extension = substr($filename, strrpos($filename,'.'),100);
			$extension = strtolower($extension);

			if (in_array($extension, $allowed_extensions)) {
				$result .= 'objImage'.$i.'.src=&quot;'.$folder.'/'.$filename.'&quot;'.&quot;\r\n&quot;;
				$i++;
			}
		}
	}
	$result .= '}';

	return($result);
}

echo load_images('../images');
?&gt;
</pre>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=Cum+fac+un+meniu+de+navigare+in+PHP%2C+CSS%2C+HTML%3F+http://fon88.th8.us" title="Publica acest articol pe Twitter"><img class="nothumb" src="http://www.accesinterzis.ro/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=Cum+fac+un+meniu+de+navigare+in+PHP%2C+CSS%2C+HTML%3F+http://fon88.th8.us" title="Publica acest articol pe Twitter">Publica acest articol pe Twitter</a></p>

<p><strong>Articole asemanatoare:<ul><li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-comentarii-versiunea-2/' rel='bookmark' title='Permanent Link: Cum fac un formular de comentarii? (versiunea 2)'>Cum fac un formular de comentarii? (versiunea 2)</a></li>
</ul></p>]]></content:encoded>
			<wfw:commentRss>http://www.accesinterzis.ro/index.php/programare/cum-fac-un-meniu-de-navigare-in-php-css-html/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cum fac un formular de autentificare a utilizatorilor?</title>
		<link>http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-autentificare-a-utilizatorilor/</link>
		<comments>http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-autentificare-a-utilizatorilor/#comments</comments>
		<pubDate>Thu, 04 Mar 2010 18:54:31 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[programare]]></category>
		<category><![CDATA[backend]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.accesinterzis.ro/?p=246</guid>
		<description><![CDATA[UPDATED ARTICLE
Un website (website de prezentare, blog, forum, magazin online, portal) este alcatuit din doua parti:

frontend &#8211; este  partea publica a unui website unde se gaseste tot continutul lui (text, imagini, video, animatii Flash). Frontend-ul este destinat vizitatorilor. De exemplu, frontend-ul unui website de prezentare al unei firme este constituit din toate paginile sale cum [...]


<strong>Articole asemanatoare:<ul><li><a href='http://www.accesinterzis.ro/index.php/web/cum-fac-un-formular-de-autentificare-a-utilizatorilor-versiunea-2/' rel='bookmark' title='Permanent Link: Cum fac un formular de autentificare a utilizatorilor? (versiunea 2)'>Cum fac un formular de autentificare a utilizatorilor? (versiunea 2)</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-inregistrare-a-utilizatorilor/' rel='bookmark' title='Permanent Link: Cum fac un formular de inregistrare a utilizatorilor?'>Cum fac un formular de inregistrare a utilizatorilor?</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/web/cum-fac-un-formular-de-inregistrare-a-utilizatorilor-versiunea-2/' rel='bookmark' title='Permanent Link: Cum fac un formular de inregistrare a utilizatorilor? (versiunea 2)'>Cum fac un formular de inregistrare a utilizatorilor? (versiunea 2)</a></li>
</ul>]]></description>
			<content:encoded><![CDATA[<p><span style="color: #ff0000;"><strong>UPDATED ARTICLE</strong></span></p>
<p>Un website (website de prezentare, blog, forum, magazin online, portal) este alcatuit din doua parti:</p>
<ul>
<li><strong>frontend</strong> &#8211; este  partea publica a unui website unde se gaseste tot continutul lui (text, imagini, video, animatii Flash). Frontend-ul este destinat <strong>vizitatorilor</strong>. De exemplu, frontend-ul unui website de prezentare al unei firme este constituit din toate paginile sale cum ar fi pagina &#8220;Despre&#8221; (unde firma prezinta istoricul firmei si profilul de activitate al firmei), pagina &#8220;Portofoliu&#8221; (unde firma prezinta lucrarile realizate si proiectele in curs de realizare), pagina &#8220;Galerie&#8221; (unde vizitatorul gaseste o galerie de imagini cu produsele firmei), pagina &#8220;Contact&#8221; (unde vizitatorul poate intra in legatura cu detinatorii firmei) s.a.m.d..</li>
<li><strong>backend</strong> &#8211; este partea cu acces restrictionat din spatele websiteului pe care numai un numar limitat de <strong>utilizatori</strong> o pot accesa pe baza unei autentificari. Din backend se administreaza continutul de pe frontend si chiar se pot face modificari asupra designului, structurii si functionalitatii frontend-ului in sine. Spre deosebire de frontend, backend-ul nu trebuie sa fie indexat de motoarele de cautare (Google, Yahoo, Bing, Ask.com etc.). Ca sa evitam acest lucru vom scrie in fisierul robots.txt din folderul radacina a websiteului urmatoarele linii:
<pre class="brush: plain;">
User-agent: *
Disallow: /backend/
</pre>
</li>
</ul>
<p>In loc de termenul <strong>backend</strong> se mai folosesc termenii <strong>sectiune de administrare</strong> si <strong>CMS </strong>(de la Content Managment System &#8211; in limba engleza, Sistem de gestionare a continutului). Cand intalnim unul din acesti termeni trebuie sa stim ca se face referire la unul si acelasi lucru.</p>
<p>Ca sa restrictionam accesul la sectiunea de administrare <a title="Cum fac un formular de inregistrare a utilizatorilor unei sectiuni de administrare?" href="http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-inregistrare-a-utilizatorilor/" target="_blank">trebuie mai intai sa inregistram toti utilizatorii intr-o baza de date</a>. Apoi cream un <a title="Cum fac un formular de autentificare a utilizatorilor?" href="http://www.accesinterzis.ro/myportofolio/loginf-v.2.0.php" target="_blank">formular de autentificare</a> a utilizatorilor sectiunii de administrare si un tabel, numit <strong>ai_authentication_logs</strong>, in care vom inregistra loguri despre autentificarile facute.</p>
<pre class="brush: php;">
$q = &quot;CREATE TABLE IF NOT EXISTS ai_authentication_logs(
		authentication_log_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
		username VARCHAR(30) NOT NULL,
		password VARCHAR(40) NOT NULL,
		server_authentication_date DATETIME NOT NULL,
		client_authentication_date DATETIME NOT NULL,
		ip VARCHAR(30) NOT NULL,
		browser_os VARCHAR(255) NOT NULL,
		screen_resolution VARCHAR(15) NOT NULL,
		status VARCHAR(10) NOT NULL,
		PRIMARY KEY(authentication_log_id))&quot;;

mysql_query($q) or die(mysql_error());
</pre>
<p><span id="more-246"></span></p>
<p>Acest tabel ne permite sa tinem o evidenta a celor care utilizeaza sectiunea de administrare. De fiecare data cand cineva se autentifica se introduce in baza de date numele utilizatorului, parola encriptata a utilizatorului, data si ora autentificarii (atat ora de pe server cat si ora de pe PC-ul utilizatorului), IP-ul de pe care s-a facut autentificarea, browserul si sistemul de operare folosite de utilizator, rezolutia monitorului utilizatorului, statusul autentificarii (reusita sau esuata).</p>
<p>Daca o autentificare esueaza parola va fi inregistrata in clar. Astfel putem vedea daca cineva doreste sa intre neautorizat in sectiunea de administrare si cu ce cuvinte incearca sa sparga parola. Se stie foarte bine ca o parola poate fi aflata prin forta bruta (<strong>brute force attack</strong>), utilizand un dictionar de cuvinte (<strong>dictionary attack</strong>) sau prin inginerie sociala (<strong>social engineering</strong>) sau poate fi pur si simplu ghicita. De asemenea un utilizator poate sa isi infecteze PC-ul cu un <strong>keylogger</strong> si astfel un rau-voitor sa intre in posesia datelor sale de logare.</p>
<p>Mai pe scurt, acest tabel ne ajuta sa vedem daca se intampla ceva suspicios in legatura cu utilizatorii sectiunii de administrare.</p>
<p>In cazul in care autentificarea reuseste, se va crea o sesiune pe server, se va salva in sesiune numele utilizatorului si browserul si sistemul de operare folosite de utilizator si se va face redirectionarea de la pagina de login la pagina principala a sectiunii de administrare.</p>
<p>Apoi pe pagina principala a sectiunii de administrare, deasupra DOCTYPE-ului mai exact, exista un script PHP care verifica daca cel care vrea sa deschida pagina este autorizat sau nu sa faca acest lucru. Daca este autorizat pagina va fi afisata in browser, daca nu este autorizat va fi redirectionat catre pagina de login. Acest script PHP il punem in toate paginile sectiunii de administrare, deasupra DOCTYPE-ului, pentru a restrictiona accesul la ele.</p>
<p>Se prefera utilizarea sesiunilor in detrimentul cookie-urilor deoarece datele de logare ale utilizatorului sunt stocate pe server si nu pe PC-ul utilizatorului. In acest fel datele de logare sunt infinit mai protejate si nu sunt transmise in mod repetat intre server si browser. Pe PC-ul utilizatorului se creeaza doar un cookie cu identificatorul sesiunii. Numele acestui cookie este <strong>PHPSESSID</strong> si valoarea stocata de cookie este o valoare de genul <strong>a76b45cf92d87ea710fc8e9a9f812fa</strong> (32 de caractere hexazecimale). Existenta acestui cookie se poate verifica din browser.</p>
<p>Pentru ca acest script PHP de autentificare sa fie complet functional mai am nevoie de <a title="Cum ma conectez la o baza de date MySQL?" href="http://www.accesinterzis.ro/index.php/programare/cum-ma-conectez-la-o-baza-de-date/" target="_blank">fisierul care ma conecteaza la baza de date</a>, <strong>connect_to_db.inc.php</strong>, pe care il apelez cu functia include().</p>
<p><strong>loginform.php</strong> &#8211; pagina cu formularul de autentificare</p>
<pre class="brush: php;">
&lt;?php
/*
Titlu: Cum fac un formular de autentificare a utilizatorilor?
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, in caz ca autentificarea reuseste, numele utilizatorului si browserul si sistemul de operare folosite de utilizator
#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 si cookie-urile 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;

$cookie = array();
foreach ($_COOKIE as $k =&gt; $v) {
	$v = htmlentities(strip_tags($v), ENT_QUOTES, 'utf-8');

	$cookie[$k] = $v;
}

//-----specific EXACT cu ce campuri se va lucra
#4
$required_fields = array('username', 'password', 'login');
$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 &amp;&amp; $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['username'])) {
		$errors['username'] = 'You forgot to enter the &lt;strong&gt;username&lt;/strong&gt;.';
	} else {
		$post['username'] = trim($_POST['username']);

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

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

	if (empty($_POST['password'])) {
		$errors['password'] = 'You forgot to enter the &lt;strong&gt;password&lt;/strong&gt;.';
	} else {
		$post['password'] = trim($_POST['password']);

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

		if (strlen($post['password']) &lt; 5) {
			$errors['password'] = 'The &lt;strong&gt;password&lt;/strong&gt; is too short.';
		} else {
			if (strlen($post['password']) &gt; 30) {
				$errors['password'] = 'The &lt;strong&gt;password&lt;/strong&gt; is too long.';
			} else {
				if (!preg_match('/^[a-z0-9][a-z0-9_ ]*[a-z0-9]$/i', $post['password'])) {
					$errors['password'] = 'The &lt;strong&gt;password&lt;/strong&gt; isn\'t valid.';
				}
			}
		}
	}

	//------daca nu exista niciun fel de erori bag datele in baza de date
    #4.3
	if (count($errors) == 0) {
		//-----verific daca datele de logare exista si in baza de date
		#4.3.1
		$q = &quot;SELECT username FROM ai_registrationform WHERE username='&quot;.$post['username'].&quot;' AND password=SHA('&quot;.$post['password'].&quot;')&quot;;
		$result = mysql_query($q) or die(mysql_error());
		$row = mysql_fetch_array($result);

		/*
		Daca autentificarea s-a efetuat cu succes:
		- salvez in tabelul de loguri un log despre autetificare
		- salvez in sesiune numele utilizatorului si numele browserului si sistemului de operare pe care le foloseste
		- redirectez utilizatorul de pe pagina de login pe pagina principala a sectiunii de administrare
		*/
		if ($row) {
			$q2 = &quot;INSERT INTO ai_authentication_logs(`username`, `password`, `server_authentication_date`, `client_authentication_date`, `ip`, `browser_os`, `screen_resolution`, `status`)&quot;
				 .&quot;VALUES('&quot;.$post['username'].&quot;', SHA('&quot;.$post['password'].&quot;'), NOW(), '&quot;.$cookie['client_authentication_date'].&quot;', '&quot;.$_SERVER['REMOTE_ADDR'].&quot;', '&quot;.$_SERVER['HTTP_USER_AGENT'].&quot;', '&quot;.$cookie['screen_resolution'].&quot;', 'succesful')&quot;;

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

			$_SESSION['username'] = $row['username'];
			$_SESSION['browser_os'] = sha1($_SERVER['HTTP_USER_AGENT']);

			header('Location:http://'.$_SERVER['HTTP_HOST'].dirname($php_self).'/backend.php');
			exit();
		} else {
			$q2 = &quot;INSERT INTO ai_authentication_logs(`username`, `password`, `server_authentication_date`, `client_authentication_date`, `ip`, `browser_os`, `screen_resolution`, `status`)&quot;
				 .&quot;VALUES('&quot;.$post['username'].&quot;', '&quot;.$post['password'].&quot;', NOW(), '&quot;.$cookie['client_authentication_date'].&quot;', '&quot;.$_SERVER['REMOTE_ADDR'].&quot;', '&quot;.$_SERVER['HTTP_USER_AGENT'].&quot;', '&quot;.$cookie['screen_resolution'].&quot;', 'failed')&quot;;

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

			$error_message = 'Your login data are wrong.';
			$errors['username'] = '';
			$errors['password'] = '';
		}
	}

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

&lt;style type=&quot;text/css&quot;&gt;
* {
	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 AUTENTIFICARE*/

div#loginf {
	width:285px;
	margin:0px auto;
}

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

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

div#loginf label {
	width:80px;
	float:left;
}

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

div#loginf input {
	width:200px;
}

div#loginf textarea {
	width:300px;
	height:150px;
}

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

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

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

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

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

div#loginf div#username_field label,
div#loginf div#password_field label {
	color:#c00;
}

div#loginf div#username_field input,
div#loginf div#password_field input {
	border:1px #c00 solid;
	color:#c00;
}

div#loginf div#username_field input:hover,
div#loginf div#password_field input:hover {
	border:1px #c00 solid;
}
/*Sfarsit - stilurile erorilor*/

/*SFARSIT - LINIILE CSS CARE CREEAZA SKINUL FORMULARULUI DE AUTENTIFICARE*/
&lt;/style&gt;

&lt;script type=&quot;text/javascript&quot;&gt;
/*
Creez cookie-urile care vor stoca date despre utilizator.
Aceste cookie-uri se creeaza atunci cand se deschide prima oara pagina de login.
De abia cand se reincarca pagina, adica cand utilizatorul apasa butonul &quot;login&quot;, scriptul PHP
se poate folosi de aceste cookie-uri.
*/
document.cookie = 'screen_resolution=' + screen.width + '*' + screen.height + ';';

var current_date = new Date();
var year = current_date.getFullYear();
var month = current_date.getMonth();
var day = current_date.getDate();
var hour = current_date.getHours();
var minutes = current_date.getMinutes();
var seconds = current_date.getSeconds();
var current_date = year + '-' + month + '-' + day + ' ' + hour + ':' + minutes + ':' + seconds;
document.cookie = 'client_authentication_date=' + current_date + ';';
&lt;/script&gt;
&lt;/head&gt;

&lt;body&gt;
&lt;div id=&quot;loginf&quot;&gt;
	&lt;h1&gt;
		&lt;label&gt;&amp;nbsp;&lt;/label&gt;
		Login
	&lt;/h1&gt;

	&lt;?php if (isset($error_message)) echo '&lt;p&gt;'.$error_message.'&lt;/p&gt;'; ?&gt;

	&lt;form action=&quot;&lt;?php echo 'http://'.$_SERVER['HTTP_HOST'].$php_self; ?&gt;&quot; method=&quot;post&quot;&gt;
		&lt;?php echo (isset($errors['username'])) ? '&lt;p&gt;'.$errors['username'].'&lt;/p&gt;&lt;div id=&quot;username_field&quot;&gt;' : '&lt;div&gt;' ; ?&gt;
			&lt;label for=&quot;username&quot;&gt;Username&lt;span&gt;*&lt;/span&gt;:&lt;/label&gt;
			&lt;input name=&quot;username&quot; type=&quot;text&quot; id=&quot;username&quot; value=&quot;&lt;?php if (isset($post['username'])) echo $post['username']; ?&gt;&quot; /&gt;
		&lt;/div&gt;

		&lt;?php echo (isset($errors['password'])) ? '&lt;p&gt;'.$errors['password'].'&lt;/p&gt;&lt;div id=&quot;password_field&quot;&gt;' : '&lt;div&gt;' ; ?&gt;
			&lt;label for=&quot;password&quot;&gt;Password&lt;span&gt;*&lt;/span&gt;:&lt;/label&gt;
			&lt;input name=&quot;password&quot; type=&quot;password&quot; id=&quot;password&quot; /&gt;
		&lt;/div&gt;

		&lt;div&gt;
			&lt;label&gt; &amp;nbsp; &lt;/label&gt;
			&lt;input name=&quot;login&quot; type=&quot;submit&quot; id=&quot;login&quot; value=&quot;login&quot; /&gt;
		&lt;/div&gt;
	&lt;/form&gt;
&lt;/div&gt;
&lt;/html&gt;
</pre>
<p><strong> backend.php</strong> &#8211; pagina principala a sectiunii de administrare</p>
<pre class="brush: php;">
&lt;?php
#1
session_start();
$php_self = htmlentities(strip_tags($_SERVER['PHP_SELF']), ENT_QUOTES, 'utf-8');
$browser_os = htmlentities(strip_tags($_SERVER['HTTP_USER_AGENT']), ENT_QUOTES, 'utf-8');

#2
if (!isset($_SESSION['username']) || !isset($_SESSION['browser_os']) || $_SESSION['browser_os'] != sha1($browser_os)) {
		header('Location:http://'.$_SERVER['HTTP_HOST'].dirname($php_self).'/loginf.php');
		exit();
}

#3
if (isset($_GET['action']) &amp;&amp; $_GET['action'] == 'logout') {
	#3.1
	/*
	Pentru a deloga un utilizator din sectiunea de administrare trebuie sa urmez pasii de mai jos:
	- distrug toate variabilele sesiunii de pe server reinitializind intregul tablou superglobal $_SESSION
	- sterg de pe server toate datele sesiunii apeland functia session_destroy()
	- sterg de pe PC-ul utilizatorului cookie-ul care stocheaza identificatorul de sesiune
	*/
	$_SESSION = array();
	if (session_destroy() &amp;&amp; setcookie('PHPSESSID', '', time()-300, '/', '', 0)) {
		header('Location:http://'.$_SERVER['HTTP_HOST'].dirname($php_self).'/loginf.php');
		exit();
	}
}
?&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Backend&lt;/title&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot; /&gt;
&lt;meta name=&quot;description&quot; content=&quot;How do I make a backend?&quot; /&gt;
&lt;meta name=&quot;keywords&quot; content=&quot;backend,administration,section,admin,cms,content,managament,system,php,script,mysql,database&quot; /&gt;
&lt;meta name=&quot;abstract&quot; content=&quot;How do I make a backend?&quot; /&gt;
&lt;meta name=&quot;author&quot; content=&quot;AccesInterzis&quot; /&gt;
&lt;meta name=&quot;copyright&quot; content=&quot;AccesInterzis&quot; /&gt;
&lt;meta name=&quot;robots&quot; content=&quot;index,follow&quot; /&gt;
&lt;meta name=&quot;revisit-after&quot; content=&quot;7 days&quot; /&gt;

&lt;link href=&quot;http://www.accesinterzis.ro/myportofolio/css/reset.css&quot; type=&quot;text/css&quot; rel=&quot;stylesheet&quot; media=&quot;all&quot; /&gt;
&lt;style type=&quot;text/css&quot;&gt;
* {
	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 SECTIUNII DE ADMINISTRARE*/

div#backend {
	width:1000px;
	margin:10px auto;
	overflow:auto;
	border:1px #ccc solid;
	padding:10px;
}

div#backend a {
	color:#900;
	text-decoration:none;
}

div#backend ul#welcome_message {
	overflow:auto;
	list-style-type:none;
}

div#backend ul#sidebar {
	width:10%;
	float:left;
	list-style-type:none;
	border-right:1px #ccc solid;
}

div#backend div#mainarea {
	width:80%;
	float:right;
}

div#backend div#mainarea p#confirmation_message {
	width:75%;
	margin:250px auto;
}

div#backend div#footer{
	width:100%;
	float:left;
	text-align:center;
}

div.splitter {
	width:100%;
	height:1px;
	clear:both;
	float:left;
	border-top:1px #ccc solid;
	margin: 10px 0 10px 0;
}

/*SFARSIT - LINIILE CSS CARE CREEAZA SKINUL SECTIUNII DE ADMINISTRARE*/
&lt;/style&gt;
&lt;/head&gt;

&lt;body&gt;

&lt;div id=&quot;backend&quot;&gt;
	&lt;ul id=&quot;welcome_message&quot;&gt;
		&lt;li style=&quot;float:left;&quot;&gt;Welcome &lt;strong&gt;&lt;?php echo $_SESSION['username']; ?&gt;&lt;/strong&gt; to the administration section&lt;/li&gt;
		&lt;li style=&quot;float:right;&quot;&gt;&lt;a href=&quot;&lt;?php echo 'http://'.$_SERVER['HTTP_HOST'].$php_self; ?&gt;?action=logout&quot; title=&quot;Logout&quot;&gt;Logout&lt;/a&gt;&lt;/li&gt;
	&lt;/ul&gt;

	&lt;div class=&quot;splitter&quot;&gt;&lt;/div&gt;

	&lt;ul id=&quot;sidebar&quot;&gt;
		&lt;?php
		for ($i = 0; $i &lt; 40; $i++) {
			echo '&lt;li&gt;sidebar&lt;/li&gt;';
		}
		?&gt;
	&lt;/ul&gt;

	&lt;div id=&quot;mainarea&quot;&gt;
		&lt;p id=&quot;confirmation_message&quot;&gt;
		&lt;strong&gt;&lt;?php echo $_SESSION['username']; ?&gt;&lt;/strong&gt;, esti aici deoarece ai dovedit ca esti un utilizator autorizat al acestei sectiuni de administrare.
		Acum delogheaza-te si incearca sa accesezi din nou &lt;strong&gt;&lt;?php echo 'http://'.$_SERVER['HTTP_HOST'].$php_self; ?&gt;&lt;/strong&gt;.
		Vei vedea ce se intampla cand cineva neautentificat incearca sa intre in sectiunea de administrare.
		&lt;/p&gt;
	&lt;/div&gt;

	&lt;div class=&quot;splitter&quot;&gt;&lt;/div&gt;

	&lt;div id=&quot;footer&quot;&gt;
		Designed and developed by &lt;a href=&quot;http://www.accesinterzis.ro&quot; title=&quot;Programare | Web development | Web design | Securitate IT | SEO&quot; target=&quot;_blank&quot;&gt;www.accesinterzis.ro&lt;/a&gt; &amp;copy; 2010. All rights reserved.
	&lt;/div&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Pentru un mai bun managment al codului trebuie sa facem urmatoarele lucruri:</p>
<ul>
<li>scriptul PHP de deasupra DOCTYPE-ului paginii de login, care valideaza datele introduse in formular, autentifica utilizatorul si il redirectioneaza catre sectiunea de administrare, se baga intr-un fisier include si se apeleaza prin functia PHP include().
<pre class="brush: php;">
&lt;?php @include('includes/authenticate_user.inc.php'); ?&gt;
</pre>
</li>
<li>liniile CSS, care creeaza skinul formularului de autentificare, din sectiunea &lt;head&gt; &lt;/head&gt; a paginii de login se baga intr-un fisier CSS extern si se apeleaza cu tagul HTML &lt;link /&gt;.
<pre class="brush: xml;">
&lt;link href=&quot;css/login_form_design.css&quot; type=&quot;text/css&quot; rel=&quot;stylesheet&quot; media=&quot;all&quot; /&gt;
</pre>
</li>
<li>liniile Javascript, care creeaza cookie-urile cu datele despre utilizator, din sectiunea &lt;head&gt;&lt;/head&gt; a paginii de login se baga intr-un fisier JS extern si se apeleaza cu tagul HTML &lt;script&gt;.
<pre class="brush: xml;">
&lt;script type=&quot;text/javascript&quot; src=&quot;js/user_data.js&quot;&gt;&lt;/script&gt;
</pre>
</li>
<li>scriptul PHP de deasupra DOCTYPE-ului paginilor ce alcatuiesc sectiunea de administrare, care permite doar utilizatorilor autentificati sa intre in sectiunea de administrare si realizeaza si functia de logout, se baga intr-un fisier include si se apeleaza prin functia PHP include().
<pre class="brush: php;">
&lt;?php @include('includes/restricted_area.inc.php'); ?&gt;
</pre>
</li>
<li>liniile CSS, care creeaza skinul sectiunii de administrare, din sectiunea &lt;head&gt; &lt;/head&gt;se baga intr-un fisier CSS extern si se apeleaza cu tagul HTML &lt;link /&gt;.
<pre class="brush: xml;">
&lt;link href=&quot;css/backend_design.css&quot; type=&quot;text/css&quot; rel=&quot;stylesheet&quot; media=&quot;all&quot; /&gt;
</pre>
</li>
</ul>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=Cum+fac+un+formular+de+autentificare+a+utilizatorilor%3F+http://qkzmc.th8.us" title="Publica acest articol pe Twitter"><img class="nothumb" src="http://www.accesinterzis.ro/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=Cum+fac+un+formular+de+autentificare+a+utilizatorilor%3F+http://qkzmc.th8.us" title="Publica acest articol pe Twitter">Publica acest articol pe Twitter</a></p>

<p><strong>Articole asemanatoare:<ul><li><a href='http://www.accesinterzis.ro/index.php/web/cum-fac-un-formular-de-autentificare-a-utilizatorilor-versiunea-2/' rel='bookmark' title='Permanent Link: Cum fac un formular de autentificare a utilizatorilor? (versiunea 2)'>Cum fac un formular de autentificare a utilizatorilor? (versiunea 2)</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-inregistrare-a-utilizatorilor/' rel='bookmark' title='Permanent Link: Cum fac un formular de inregistrare a utilizatorilor?'>Cum fac un formular de inregistrare a utilizatorilor?</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/web/cum-fac-un-formular-de-inregistrare-a-utilizatorilor-versiunea-2/' rel='bookmark' title='Permanent Link: Cum fac un formular de inregistrare a utilizatorilor? (versiunea 2)'>Cum fac un formular de inregistrare a utilizatorilor? (versiunea 2)</a></li>
</ul></p>]]></content:encoded>
			<wfw:commentRss>http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-autentificare-a-utilizatorilor/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Cum fac un formular de inregistrare a utilizatorilor?</title>
		<link>http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-inregistrare-a-utilizatorilor/</link>
		<comments>http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-inregistrare-a-utilizatorilor/#comments</comments>
		<pubDate>Tue, 02 Mar 2010 14:56:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[programare]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.accesinterzis.ro/?p=206</guid>
		<description><![CDATA[UPDATED ARTICLE
Prin ce se caracterizeaza acest formular de inregistrare a utilizatorilor?

scriptul PHP isi creeaza singur tabelul in care va stoca utilizatorii daca acesta nu exista in baza de date
toate datele introduse sunt validate server-side
scriptul verifica in baza de date daca exista deja numele de utilizator ales si adresa de email a noului utilizator
fiecare mesaj de eroare [...]


<strong>Articole asemanatoare:<ul><li><a href='http://www.accesinterzis.ro/index.php/web/cum-fac-un-formular-de-inregistrare-a-utilizatorilor-versiunea-2/' rel='bookmark' title='Permanent Link: Cum fac un formular de inregistrare a utilizatorilor? (versiunea 2)'>Cum fac un formular de inregistrare a utilizatorilor? (versiunea 2)</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-autentificare-a-utilizatorilor/' rel='bookmark' title='Permanent Link: Cum fac un formular de autentificare a utilizatorilor?'>Cum fac un formular de autentificare a utilizatorilor?</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-comentarii/' rel='bookmark' title='Permanent Link: Cum fac un formular de comentarii?'>Cum fac un formular de comentarii?</a></li>
</ul>]]></description>
			<content:encoded><![CDATA[<p><span style="color: #ff0000;"><strong>UPDATED ARTICLE</strong></span></p>
<p>Prin ce se caracterizeaza acest formular de inregistrare a utilizatorilor?</p>
<ul>
<li>scriptul PHP isi creeaza singur tabelul in care va stoca utilizatorii daca acesta nu exista in baza de date</li>
<li>toate datele introduse sunt validate server-side</li>
<li>scriptul verifica in baza de date daca exista deja numele de utilizator ales si adresa de email a noului utilizator</li>
<li>fiecare mesaj de eroare este personalizat pentru fiecare eroare in parte</li>
<li>campurile care contin date invalide sunt evidentiate</li>
<li>scriptul pastreaza datele introduse in campurile formularului atunci cand detecteaza o eroare</li>
<li>designul formularului este creat EXCLUSIV din CSS</li>
<li>de protectie antispam nu avem nevoie deoarece se presupune ca formularul de inregistrare se afla in interiorul unei sectiuni de administrare</li>
</ul>
<p><span id="more-206"></span></p>
<p>Asadar, ca sa realizez un formular de inregistrare a utilizatorilor mai intai creez in baza de date tabelul care va stoca toti utilizatorii.</p>
<pre class="brush: php;">
$q = &quot;CREATE TABLE IF NOT EXISTS ai_registrationform(
		user_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
		username VARBINARY(30) NOT NULL,
		email VARCHAR(30) NOT NULL,
		password CHAR(40) NOT NULL,
		registration_date DATETIME NOT NULL,
		ip VARCHAR(16) NOT NULL,
		PRIMARY KEY(user_id))&quot;;

mysql_query($q) or die(mysql_error());
</pre>
<p>Mai avem nevoie de <a title="Cum ma conectez la o baza de date?" href="http://www.accesinterzis.ro/index.php/programare/cum-ma-conectez-la-o-baza-de-date/" target="_blank">connect_to_db.inc.php</a>, fisierul care ne conecteaza la baza de date.</p>
<pre class="brush: php;">
&lt;?php
/*
Titlu: Cum fac un formular de inregistrare a utilizatorilor?
Autor: Marian Barbu aka AccesInterzis
Website: http://www.accesinterzis.ro
2010 (c) Toate drepturile rezervate
*/

//-----ma conectez la baza de date
#1
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
#2
$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
#3
$required_fields = array('username', 'email', 'password', 'retype_password', 'register');
$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
#4
if ($referer == 'http://'.$_SERVER['HTTP_HOST'].$php_self &amp;&amp; $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['username'])) {
		$errors['username'] = 'You forgot to enter the &lt;strong&gt;username&lt;/strong&gt;.';
	} else {
		$post['username'] = trim($_POST['username']);

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

		if (strlen($post['username']) &lt; 3) {
			$errors['username'] = 'The &lt;strong&gt;username&lt;/strong&gt; is too short.';
		} else {
			if (strlen($post['username']) &gt; 30) {
				$errors['username'] = 'The &lt;strong&gt;username&lt;/strong&gt; is too long.';
			} else {
				if (!preg_match('/[a-z0-9_ ]*/i', $post['username'])) {
					$errors['username'] = 'The &lt;strong&gt;username&lt;/strong&gt; isn\'t valid.';
				} else {
					$q = &quot;SELECT user_id FROM ai_registrationform WHERE LOWER(username)='&quot;.strtolower($post['username']).&quot;'&quot;;
                    $result = mysql_query($q) or die(mysql_error());

                    if (mysql_num_rows($result) != 0) {
						$errors['username'] = 'The username &lt;strong&gt;'.$post['username'].'&lt;/strong&gt; already exists in our database.';
					}
				}
			}
		}
	}

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

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

		if (strlen($post['email']) &lt; 3) {
			$errors['email'] = 'The &lt;strong&gt;email address&lt;/strong&gt; is too short.';
		} else {
			if (strlen($post['email']) &gt; 30) {
				$errors['email'] = 'The &lt;strong&gt;email address&lt;/strong&gt; 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 &lt;strong&gt;email address&lt;/strong&gt; isn\'t valid.';
				} else {
					$q = &quot;SELECT user_id FROM ai_registrationform WHERE LOWER(email)='&quot;.strtolower($post['email']).&quot;'&quot;;
                    $result = mysql_query($q) or die(mysql_error());

                    if (mysql_num_rows($result) != 0) {
						$errors['username'] = 'The email address &lt;strong&gt;'.$post['email'].'&lt;/strong&gt; already exists in our database.';
					}
				}
			}
		}
	}

	if (empty($_POST['password'])) {
		$errors['password'] = 'You forgot to enter the &lt;strong&gt;password&lt;/strong&gt;.';
	} else {
		$post['password'] = trim($_POST['password']);

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

		if (strlen($post['password']) &lt; 5) {
			$errors['password'] = 'The &lt;strong&gt;password&lt;/strong&gt; is too short.';
		} else {
			if (strlen($post['password']) &gt; 30) {
				$errors['password'] = 'The &lt;strong&gt;password&lt;/strong&gt; is too long.';
			} else {
				if (!preg_match('/^[a-z0-9][a-z0-9_ ]*[a-z0-9]$/i', $post['password'])) {
					$errors['password'] = 'The &lt;strong&gt;password&lt;/strong&gt; isn\'t valid.';
				} else {
					if ($post['password'] != $_POST['retype_password']) {
						$errors['password'] = 'The two passwords don\'t match.';
						$errors['retype_password'] = '';
					}
				}
			}
		}
	}
	//Ending data validation

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

		#4.3.2
		$q = &quot;INSERT INTO ai_registrationform(`username`, `email`, `password`, `registration_date`, `ip`)&quot;
			.&quot;VALUES('&quot;.$post['username'].&quot;', '&quot;.$post['email'].&quot;', SHA('&quot;.$post['password'].&quot;'), NOW(), '&quot;.$_SERVER['REMOTE_ADDR'].&quot;')&quot;;

		#4.3.3
		if (mysql_query($q)) {
			$confirmation = 'The user &lt;strong&gt;'.$post['username'].'&lt;/strong&gt; was succesfully registered in our databse.';
		} else {
			$confirmation = 'Something is wrong with the server. The user &lt;strong&gt;'.$post['username'].'&lt;/strong&gt; wasn\'t registered.';
		}

		$confirmation .= ' &lt;a href=&quot;http://'.$_SERVER['HTTP_HOST'].$php_self.'&quot; title=&quot;Back&quot; id=&quot;back&quot;&gt;Back to registration form&lt;/a&gt;';

		$display = 'style=&quot;display:none;&quot;';
	}

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

&lt;style type=&quot;text/css&quot;&gt;
* {
	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 INREGISTRARE*/

div#registrationf {
	width:335px;
	margin:0px auto;
}

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

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

div#registrationf label {
	width:130px;
	float:left;
}

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

div#registrationf input {
	width:200px;
}

div#registrationf textarea {
	width:300px;
	height:150px;
}

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

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

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

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

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

div#registrationf div#username_field label,
div#registrationf div#email_field label,
div#registrationf div#password_field label,
div#registrationf div#retype_password_field label {
	color:#c00;
}

div#registrationf div#username_field input,
div#registrationf div#email_field input,
div#registrationf div#password_field input,
div#registrationf div#retype_password_field input {
	border:1px #c00 solid;
	color:#c00;
}

div#registrationf div#username_field input:hover,
div#registrationf div#email_field input:hover,
div#registrationf div#password_field input:hover,
div#registrationf div#retype_password_field input:hover {
	border:1px #c00 solid;
}
/*Sfarsit - stilurile erorilor*/

div#registrationf a#back {
	color:#900;
	font-weight:bold;
	text-decoration:underline;
}

/*SFARSIT - LINIILE CSS CARE CREEAZA SKINUL FORMULARULUI DE INREGISTRARE*/
&lt;/style&gt;
&lt;/head&gt;

&lt;body&gt;
&lt;div id=&quot;registrationf&quot;&gt;
	&lt;h1&gt;
		&lt;label&gt;&amp;nbsp;&lt;/label&gt;
		Register an user
	&lt;/h1&gt;

	&lt;?php if (isset($confirmation)) echo '&lt;p&gt;'.$confirmation.'&lt;/p&gt;'; ?&gt;

	&lt;form action=&quot;&lt;?php echo 'http://'.$_SERVER['HTTP_HOST'].$php_self; ?&gt;&quot; method=&quot;post&quot; &lt;?php if (isset($display)) echo $display; ?&gt;&gt;
		&lt;?php echo (isset($errors['username'])) ? '&lt;p&gt;'.$errors['username'].'&lt;/p&gt;&lt;div id=&quot;username_field&quot;&gt;' : '&lt;div&gt;' ; ?&gt;
			&lt;label for=&quot;username&quot;&gt;Username&lt;span&gt;*&lt;/span&gt;:&lt;/label&gt;
			&lt;input name=&quot;username&quot; type=&quot;text&quot; id=&quot;username&quot; value=&quot;&lt;?php if (isset($post['username'])) echo $post['username']; ?&gt;&quot; /&gt;
		&lt;/div&gt;

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

		&lt;?php echo (isset($errors['password'])) ? '&lt;p&gt;'.$errors['password'].'&lt;/p&gt;&lt;div id=&quot;password_field&quot;&gt;' : '&lt;div&gt;' ; ?&gt;
			&lt;label for=&quot;password&quot;&gt;Password&lt;span&gt;*&lt;/span&gt;:&lt;/label&gt;
			&lt;input name=&quot;password&quot; type=&quot;password&quot; id=&quot;password&quot; /&gt;
		&lt;/div&gt;

		&lt;?php echo (isset($errors['retype_password'])) ? '&lt;p&gt;'.$errors['retype_password'].'&lt;/p&gt;&lt;div id=&quot;retype_password_field&quot;&gt;' : '&lt;div&gt;' ; ?&gt;
			&lt;label for=&quot;retype_password&quot;&gt;Retype password&lt;span&gt;*&lt;/span&gt;:&lt;/label&gt;
			&lt;input name=&quot;retype_password&quot; type=&quot;password&quot; id=&quot;retype_password&quot; /&gt;
		&lt;/div&gt;

		&lt;div&gt;
			&lt;label&gt; &amp;nbsp; &lt;/label&gt;
			&lt;input name=&quot;register&quot; type=&quot;submit&quot; id=&quot;register&quot; value=&quot;register&quot; /&gt;
		&lt;/div&gt;
	&lt;/form&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Pentru un mai bun managment al codului este indicat ca scriptul PHP de deasupra DOCTYPE-ului, care valideaza datele introduse in formular si inregistreaza utilizatorul in baza de date, sa se bage intr-un fisier include si sa fie apelat prin functia PHP include().</p>
<pre class="brush: php;">
&lt;?php @include('includes/register_user.inc.php'); ?&gt;
</pre>
<p>De asemenea, este indicat ca liniile CSS, care creeaza skinul formularului de inregistrare, din sectiunea &lt;head&gt; &lt;/head&gt; sa fie bagate intr-un fisier CSS extern si apelate cu tagul HTML &lt;link /&gt;.</p>
<pre class="brush: xml;">
&lt;link href=&quot;css/registration_form_design.css&quot; type=&quot;text/css&quot; rel=&quot;stylesheet&quot; media=&quot;all&quot; /&gt;
</pre>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=Cum+fac+un+formular+de+inregistrare+a+utilizatorilor%3F+http://nzgae.th8.us" title="Publica acest articol pe Twitter"><img class="nothumb" src="http://www.accesinterzis.ro/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=Cum+fac+un+formular+de+inregistrare+a+utilizatorilor%3F+http://nzgae.th8.us" title="Publica acest articol pe Twitter">Publica acest articol pe Twitter</a></p>

<p><strong>Articole asemanatoare:<ul><li><a href='http://www.accesinterzis.ro/index.php/web/cum-fac-un-formular-de-inregistrare-a-utilizatorilor-versiunea-2/' rel='bookmark' title='Permanent Link: Cum fac un formular de inregistrare a utilizatorilor? (versiunea 2)'>Cum fac un formular de inregistrare a utilizatorilor? (versiunea 2)</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-autentificare-a-utilizatorilor/' rel='bookmark' title='Permanent Link: Cum fac un formular de autentificare a utilizatorilor?'>Cum fac un formular de autentificare a utilizatorilor?</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-comentarii/' rel='bookmark' title='Permanent Link: Cum fac un formular de comentarii?'>Cum fac un formular de comentarii?</a></li>
</ul></p>]]></content:encoded>
			<wfw:commentRss>http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-inregistrare-a-utilizatorilor/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Cum fac un formular de comentarii?</title>
		<link>http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-comentarii/</link>
		<comments>http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-comentarii/#comments</comments>
		<pubDate>Mon, 01 Mar 2010 21:34:29 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[programare]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.accesinterzis.ro/?p=144</guid>
		<description><![CDATA[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 [...]


<strong>Articole asemanatoare:<ul><li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-comentarii-versiunea-2/' rel='bookmark' title='Permanent Link: Cum fac un formular de comentarii? (versiunea 2)'>Cum fac un formular de comentarii? (versiunea 2)</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-inregistrare-a-utilizatorilor/' rel='bookmark' title='Permanent Link: Cum fac un formular de inregistrare a utilizatorilor?'>Cum fac un formular de inregistrare a utilizatorilor?</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-contact/' rel='bookmark' title='Permanent Link: Cum fac un formular de contact?'>Cum fac un formular de contact?</a></li>
</ul>]]></description>
			<content:encoded><![CDATA[<p><span style="color: #ff0000;"><strong>UPDATED ARTICLE</strong></span></p>
<p>Prin ce se caracterizeaza acest formular de comentarii?</p>
<ul>
<li>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)</li>
<li>protectie antispam 100% datorita sistemului CAPTCHA integrat</li>
<li>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)</li>
<li>evidentierea campurilor care contin date invalide</li>
<li>pastrarea datelor in campuri atunci cand scriptul detecteaza o eroare</li>
<li>background-ul fiecarui comentariu alterneaza de la un comentariu la altul pentru o mai buna vizualizare a comentariilor</li>
<li>designul formularului este creat EXCLUSIV din CSS</li>
</ul>
<p><span id="more-144"></span></p>
<p>Asadar, ca sa realizez un formular de cometarii mai intai creez in baza de date tabelul care va stoca toate comentariile.</p>
<pre class="brush: php;">
$q = &quot;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))&quot;;

mysql_query($q) or die(mysql_error());
</pre>
<p>Mai avem nevoie de <a title="Cum ma conectez la o baza de date?" href="http://www.accesinterzis.ro/index.php/programare/cum-ma-conectez-la-o-baza-de-date/" target="_blank">connect_to_db.inc.php</a>, fisierul care ne conecteaza la baza de date.</p>
<pre class="brush: php;">
&lt;?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 &amp;&amp; $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 &lt;strong&gt;name&lt;/strong&gt;.';
	} else {
		$post['name'] = trim($_POST['name']);

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

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

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

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

		if (strlen($post['email']) &lt; 3) {
			$errors['email'] = 'The &lt;strong&gt;email address&lt;/strong&gt; is too short.';
		} else {
			if (strlen($post['email']) &gt; 30) {
				$errors['email'] = 'The &lt;strong&gt;email address&lt;/strong&gt; 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 &lt;strong&gt;email address&lt;/strong&gt; 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']) &lt; 7) {
			$errors['website'] = 'The &lt;strong&gt;website&lt;/strong&gt; URL is too short.';
		} else {
			if (strlen($post['website']) &gt; 30) {
				$errors['website'] = 'The &lt;strong&gt;website URL&lt;/strong&gt; 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 &lt;strong&gt;comment&lt;/strong&gt;.';
	} else {
		$post['comment'] = trim($_POST['comment']);

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

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

	if (empty($_POST['security_code'])) {
		$errors['security_code'] = 'You forgot to enter the &lt;strong&gt;security code&lt;/strong&gt;.';
	} 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']) &lt; 3) {
			$errors['security_code'] = 'The &lt;strong&gt;security code&lt;/strong&gt; is too short.';
		} else {
			if (strlen($post['security_code']) &gt; 10) {
				$errors['security_code'] = 'The &lt;strong&gt;security code&lt;/strong&gt; is too long.';
			} else {
				if (!preg_match('/^[a-z0-9]*$/i', $post['security_code'])) {
					$errors['security_code'] = 'The &lt;strong&gt;security code&lt;/strong&gt; isn\'t valid.';
				} else {
					if ($_SESSION['security_code'] != $_POST['security_code']) {
						$errors['security_code'] = 'The &lt;strong&gt;security code&lt;/strong&gt; 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 =&gt; $v) {
			$post[$k] = mysql_real_escape_string($v);
		}

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

		#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 =&gt; $v) {
		$post[$k] = htmlentities(stripslashes($v), ENT_QUOTES, 'utf-8');
	}
}
?&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;How do I make a comment form?&lt;/title&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot; /&gt;
&lt;meta name=&quot;description&quot; content=&quot;How do I make a comment form?&quot; /&gt;
&lt;meta name=&quot;keywords&quot; content=&quot;comment,form,php,script,add,email&quot; /&gt;
&lt;meta name=&quot;abstract&quot; content=&quot;How do I make a comment form?&quot; /&gt;
&lt;meta name=&quot;author&quot; content=&quot;AccesInterzis&quot; /&gt;
&lt;meta name=&quot;copyright&quot; content=&quot;AccesInterzis&quot; /&gt;
&lt;meta name=&quot;robots&quot; content=&quot;index,follow&quot; /&gt;
&lt;meta name=&quot;revisit-after&quot; content=&quot;7 days&quot; /&gt;

&lt;style type=&quot;text/css&quot;&gt;
* {
	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*/
&lt;/style&gt;
&lt;/head&gt;

&lt;body&gt;
&lt;?php
$q = &quot;SELECT name, website, date, comment FROM ai_commentform ORDER BY comment_id DESC&quot;;
$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 '&lt;div id=&quot;comments&quot;&gt;';
	echo '&lt;h1&gt;'.mysql_num_rows($result).' comment(s) so far&lt;/h1&gt;';

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

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

		$i++;
	}
	echo '&lt;/div&gt;';
}
?&gt;
&lt;div id=&quot;commentf&quot;&gt;
	&lt;h1&gt;
		&lt;label&gt;&amp;nbsp;&lt;/label&gt;
		Leave a comment
	&lt;/h1&gt;

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

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

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

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

		&lt;p&gt;
			&lt;img src=&quot;includes/captchaimage.inc.php?width=120&amp;height=40&amp;characters=5&quot; /&gt;
		&lt;p&gt;

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

		&lt;div&gt;
			&lt;label&gt; &amp;nbsp; &lt;/label&gt;
			&lt;input name=&quot;add&quot; type=&quot;submit&quot; id=&quot;add&quot; value=&quot;add&quot; /&gt;
		&lt;/div&gt;
	&lt;/form&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Felul in care se integreaza sistemul CAPTCHA in formular il puteti gasi in <a title="Cum fac un formular de contact?" href="http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-contact/" target="_blank">articolul</a> care prezinta cum se realizeaza un formular de contact.</p>
<p>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().</p>
<pre class="brush: php;">
&lt;?php @include('includes/add_comment.inc.php'); ?&gt;
</pre>
<p>De asemenea, este indicat ca liniile CSS, care creeaza skinul formularului de comentarii, din sectiunea &lt;head&gt; &lt;/head&gt; sa fie bagate intr-un fisier CSS extern si apelate cu tagul HTML &lt;link /&gt;.</p>
<pre class="brush: xml;">
&lt;link href=&quot;css/comment_form_design.css&quot; type=&quot;text/css&quot; rel=&quot;stylesheet&quot; media=&quot;all&quot; /&gt;
</pre>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=Cum+fac+un+formular+de+comentarii%3F+http://5r28a.th8.us" title="Publica acest articol pe Twitter"><img class="nothumb" src="http://www.accesinterzis.ro/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=Cum+fac+un+formular+de+comentarii%3F+http://5r28a.th8.us" title="Publica acest articol pe Twitter">Publica acest articol pe Twitter</a></p>

<p><strong>Articole asemanatoare:<ul><li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-comentarii-versiunea-2/' rel='bookmark' title='Permanent Link: Cum fac un formular de comentarii? (versiunea 2)'>Cum fac un formular de comentarii? (versiunea 2)</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-inregistrare-a-utilizatorilor/' rel='bookmark' title='Permanent Link: Cum fac un formular de inregistrare a utilizatorilor?'>Cum fac un formular de inregistrare a utilizatorilor?</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-contact/' rel='bookmark' title='Permanent Link: Cum fac un formular de contact?'>Cum fac un formular de contact?</a></li>
</ul></p>]]></content:encoded>
			<wfw:commentRss>http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-comentarii/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Cum fac un formular de contact?</title>
		<link>http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-contact/</link>
		<comments>http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-contact/#comments</comments>
		<pubDate>Tue, 23 Feb 2010 15:11:55 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[programare]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.accesinterzis.ro/?p=80</guid>
		<description><![CDATA[UPDATED ARTICLE
Prin ce se caracterizeaza acest formular de contact?

toate datele sunt validate server-side
protectie antispam 100% datorita sistemului CAPTCHA integrat in formular
fiecare mesaj de eroare este personalizat pentru fiecare eroare in parte si apare deasupra campului unde a fost detectata eroarea
campul unde exista o eroare este evidentiat
datele completate raman in campurile formularului atunci cand se detecteaza o [...]


<strong>Articole asemanatoare:<ul><li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-contact-versiunea-2/' rel='bookmark' title='Permanent Link: Cum fac un formular de contact? (versiunea 2)'>Cum fac un formular de contact? (versiunea 2)</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-comentarii/' rel='bookmark' title='Permanent Link: Cum fac un formular de comentarii?'>Cum fac un formular de comentarii?</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-inregistrare-a-utilizatorilor/' rel='bookmark' title='Permanent Link: Cum fac un formular de inregistrare a utilizatorilor?'>Cum fac un formular de inregistrare a utilizatorilor?</a></li>
</ul>]]></description>
			<content:encoded><![CDATA[<p><span style="color: #ff0000;"><strong>UPDATED ARTICLE</strong></span></p>
<p>Prin ce se caracterizeaza acest formular de contact?</p>
<ul>
<li>toate datele sunt validate server-side</li>
<li>protectie antispam 100% datorita sistemului CAPTCHA integrat in formular</li>
<li>fiecare mesaj de eroare este personalizat pentru fiecare eroare in parte si apare deasupra campului unde a fost detectata eroarea</li>
<li>campul unde exista o eroare este evidentiat</li>
<li>datele completate raman in campurile formularului atunci cand se detecteaza o eroare</li>
<li>skin creat EXCLUSIV din CSS</li>
<li>formularul poate fi usor de integrat intr-un website</li>
<li>skinul emailului trimis poate fi formatat prin folosirea tagurilor HTML si a regulilor CSS aplicate inline</li>
<li>in subsolul emailului trimis exista cateva informatii despre expeditor</li>
</ul>
<p><span id="more-80"></span></p>
<pre class="brush: php;">
&lt;?php
/*
Titlu: Cum fac un formular de contact?
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();

//-----infasor in strip_tags() si htmlentities() URL-urile obtinute dinamic si http_user_agent-ul ca sa ma asigur ca nu contin cod malitios
#2
$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;
$browser_os = htmlentities(strip_tags($_SERVER['HTTP_USER_AGENT']), ENT_QUOTES, 'utf-8');

//-----specific EXACT cu ce campuri se va lucra
#3
$required_fields = array('name', 'phone_number', 'email', 'message', 'security_code', 'send');
$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
#4
if ($referer == 'http://'.$_SERVER['HTTP_HOST'].$php_self &amp;&amp; $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
	#4.1
	$errors = array();
	$post = array();

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

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

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

	if (empty($_POST['phone_number'])) {
		$errors['phone_number'] = 'You forgot to enter the &lt;strong&gt;phone number&lt;/strong&gt;.';
	} else {
		$post['phone_number'] = trim($_POST['phone_number']);

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

		if (strlen($post['phone_number']) &lt; 3) {
			$errors['phone_number'] = 'The &lt;strong&gt;phone number&lt;/strong&gt; is too short.';
		} else {
			if (strlen($post['phone_number']) &gt; 15) {
				$errors['phone_number'] = 'The &lt;strong&gt;phone number&lt;/strong&gt; is too long.';
			} else {
				if (!preg_match('/^[0-9+][0-9.+ ]*[0-9]$/', $post['phone_number'])) {
					$errors['phone_number'] = 'The &lt;strong&gt;phone number&lt;/strong&gt; isn\'t valid.';
				}
			}
		}
	}

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

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

		if (strlen($post['email']) &lt; 3) {
			$errors['email'] = 'The &lt;strong&gt;email address&lt;/strong&gt; is too short.';
		} else {
			if (strlen($post['email']) &gt; 30) {
				$errors['email'] = 'The &lt;strong&gt;email address&lt;/strong&gt; 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 &lt;strong&gt;email address&lt;/strong&gt; isn\'t valid.';
				}
			}
		}
	}

	if (empty($_POST['message'])) {
		$errors['message'] = 'You forgot to enter the &lt;strong&gt;message&lt;/strong&gt;.';
	} else {
		$post['message'] = trim($_POST['message']);

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

		if (strlen($post['message']) &lt; 3) {
			$errors['message'] = 'The &lt;strong&gt;message&lt;/strong&gt; is too short.';
		} else {
			if (strlen($post['message']) &gt; 100000) {
				$errors['message'] = 'The &lt;strong&gt;message&lt;/strong&gt; is too long.';
			}
		}
	}

	if (empty($_POST['security_code'])) {
		$errors['security_code'] = 'You forgot to enter the &lt;strong&gt;security code&lt;/strong&gt;.';
	} 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']) &lt; 3) {
			$errors['security_code'] = 'The &lt;strong&gt;security code&lt;/strong&gt; is too short.';
		} else {
			if (strlen($post['security_code']) &gt; 10) {
				$errors['security_code'] = 'The &lt;strong&gt;security code&lt;/strong&gt; is too long.';
			} else {
				if (!preg_match('/^[a-z0-9]*$/i', $post['security_code'])) {
					$errors['security_code'] = 'The &lt;strong&gt;security code&lt;/strong&gt; isn\'t valid.';
				} else {
					if ($_SESSION['security_code'] != $_POST['security_code']) {
						$errors['security_code'] = 'The &lt;strong&gt;security code&lt;/strong&gt; entered is wrong.';
					}
				}
			}
		}
	}
	//Ending data validation

    //------daca nu exista niciun fel de erori trimit emailul
	#4.3
	if(count($errors) == 0) {
		//-----infasor datele in htmlentities() si nl2br() deoarece urmeaza sa le trimit
		#4.3.1
		foreach ($post as $k =&gt; $v) {
			$post[$k] = nl2br(htmlentities($v, ENT_QUOTES, 'utf-8'));
		}

        #4.3.2
        $to      = 'whovisitedme@gmail.com';
        $subject = substr($post['message'], 0, 20).'...';
        $body    = 'This message is received from http://'.$_SERVER['HTTP_HOST'].$php_self.'&lt;br /&gt;&lt;br /&gt;
                    &lt;strong&gt;Name&lt;/strong&gt;: '.$post['name'].'&lt;br /&gt;
                    &lt;strong&gt;Phone number&lt;/strong&gt;: '.$post['phone_number'].'&lt;br /&gt;
                    &lt;strong&gt;Email address&lt;/strong&gt;: '.$post['email'].'&lt;br /&gt;
                    &lt;strong&gt;Mesagge&lt;/strong&gt;: '.$post['message'].'&lt;br /&gt;&lt;br /&gt;
                    &lt;strong style=&quot;color:#c00;&quot;&gt;Infos about sender:&lt;/strong&gt;&lt;br /&gt;
                    &lt;strong&gt;IP address&lt;/strong&gt;: '.$_SERVER['REMOTE_ADDR'].'&lt;br /&gt;
                    &lt;strong&gt;browser and operating system&lt;/strong&gt;: '.$browser_os.'&lt;br /&gt;
                    &lt;strong&gt;dispatch hour&lt;/strong&gt;: '.date(&quot;l, F j, Y, H:i:s&quot;);
        $headers  = &quot;From: &quot;.$post['email'].&quot;\r\n&quot;;

		//-----ma asigur ca pot formata emailul cu taguri HTML si reguli CSS aplicate inline
        #4.3.3
        $headers .= 'MIME-Version: 1.0'.&quot;\r\n&quot;;
        $headers .= 'Content-type: text/html; charset=utf-8' . &quot;\r\n&quot;;

		//------daca emailul a fost intr-adevar trimis se va afisa pe monitor un mesaj de confirmare
        #4.3.4
        if (mail($to, $subject, $body, $headers)) {
			$confirmation = 'Your message was succesfully sent. We will get in touch with you as soon as possible.';
        } else {
			$confirmation = 'Something is wrong with the server. Your message wasn\'t sent.';
        }

		$confirmation .= ' &lt;a href=&quot;http://'.$_SERVER['HTTP_HOST'].$php_self.'&quot; title=&quot;Back&quot; id=&quot;back&quot;&gt;Back to contact form&lt;/a&gt;';

		#4.3.5
		$display = 'style=&quot;display:none;&quot;';
    }

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

&lt;style type=&quot;text/css&quot;&gt;
* {
	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#contactf {
	width:530px;
	margin:0px auto;
}

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

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

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

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

div#contactf input {
	width:200px;
}

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

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

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

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

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

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

div#contactf div#name_field label,
div#contactf div#email_field label,
div#contactf div#phone_number_field label,
div#contactf div#message_field label,
div#contactf div#security_code_field label {
	color:#c00;
}

div#contactf div#name_field input,
div#contactf div#email_field input,
div#contactf div#phone_number_field input,
div#contactf div#message_field textarea,
div#contactf div#security_code_field input {
	border:1px #c00 solid;
	color:#c00;
}

div#contactf div#name_field input:hover,
div#contactf div#email_field input:hover,
div#contactf div#phone_number_field input:hover,
div#contactf div#message_field textarea:hover,
div#contactf div#security_code_field input:hover {
	border:1px #c00 solid;
}

div#contactf a#back {
	color:#900;
	font-weight:bold;
	text-decoration:underline;
}
/*Sfarsit - stilurile erorilor*/

/*SFARSIT - LINIILE CSS CARE CREEAZA SKINUL FORMULARULUI DE CONTACT*/
&lt;/style&gt;
&lt;/head&gt;

&lt;body&gt;
&lt;div id=&quot;contactf&quot;&gt;
	&lt;h1&gt;
        &lt;label&gt;&amp;nbsp;&lt;/label&gt;
        Contact us
    &lt;/h1&gt;

    &lt;?php if (isset($confirmation)) echo '&lt;p&gt;'.$confirmation.'&lt;/p&gt;'; ?&gt;

	&lt;form action=&quot;&lt;?php echo 'http://'.$_SERVER['HTTP_HOST'].$php_self; ?&gt;&quot; method=&quot;post&quot; &lt;?php if (isset($display)) echo $display; ?&gt;&gt;
		&lt;?php echo (isset($errors['name'])) ? '&lt;p&gt;'.$errors['name'].'&lt;/p&gt;&lt;div id=&quot;name_field&quot;&gt;' : '&lt;div&gt;' ; ?&gt;
			&lt;label for=&quot;name&quot;&gt;Name&lt;span&gt;*&lt;/span&gt;:&lt;/label&gt;
			&lt;input name=&quot;name&quot; type=&quot;text&quot; id=&quot;name&quot; value=&quot;&lt;?php if (isset($post['name'])) echo $post['name']; ?&gt;&quot; /&gt;
		&lt;/div&gt;

		&lt;?php echo (isset($errors['phone_number'])) ? '&lt;p&gt;'.$errors['phone_number'].'&lt;/p&gt;&lt;div id=&quot;phone_number_field&quot;&gt;' : '&lt;div&gt;' ; ?&gt;
			&lt;label for=&quot;phone_number&quot;&gt;Phone number&lt;span&gt;*&lt;/span&gt;:&lt;/label&gt;
			&lt;input name=&quot;phone_number&quot; type=&quot;text&quot; id=&quot;phone_number&quot; value=&quot;&lt;?php if (isset($post['phone_number'])) echo $post['phone_number']; ?&gt;&quot; /&gt;
		&lt;/div&gt;

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

		&lt;?php echo (isset($errors['message'])) ? '&lt;p&gt;'.$errors['message'].'&lt;/p&gt;&lt;div id=&quot;message_field&quot;&gt;' : '&lt;div&gt;' ; ?&gt;
			&lt;label for=&quot;message&quot;&gt;Your message&lt;span&gt;*&lt;/span&gt;:&lt;/label&gt;
			&lt;textarea name=&quot;message&quot; rows=&quot;1&quot; cols=&quot;1&quot; id=&quot;message&quot;&gt;&lt;?php if (isset($post['message'])) echo $post['message']; ?&gt;&lt;/textarea&gt;
		&lt;/div&gt;

		&lt;p&gt;
			&lt;img src=&quot;includes/captchaimage.inc.php?width=120&amp;height=40&amp;characters=5&quot; /&gt;
		&lt;/p&gt;

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

		&lt;div&gt;
			&lt;label&gt; &amp;nbsp; &lt;/label&gt;
			&lt;input name=&quot;send&quot; type=&quot;submit&quot; id=&quot;send&quot; value=&quot;send&quot; /&gt;
		&lt;/div&gt;
	&lt;/form&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Pe langa fisierul principal de mai sus mai avem nevoie de fisierul care genereaza imaginea cu codul de securitate si anume captchaimage.inc.php care se gaseste in folderul &#8220;includes&#8221; si de fontul folosit pentru generarea codului de securitate si anume <a title="Cum fac un formular de contact?" href="http://www.accesinterzis.ro/myportofolio/includes/monofont.ttf" target="_blank">monofont.ttf</a> care trebuie sa se afle in acelasi folder cu captchaimage.inc.php.</p>
<pre class="brush: php;">
&lt;?php
/*
File: CaptchaSecurityImages.php
Author: Simon Jarvis
Copyright: 2006 Simon Jarvis
Date: 03/08/06
Updated: 07/02/07
Requirements: PHP 4/5 with GD and FreeType libraries
Link: http://www.white-hat-web-design.co.uk/articles/php-captcha.php
*/

session_start();

class CaptchaSecurityImages {

	var $font = 'monofont.ttf';

	function generateCode($characters) {
		/* list all possible characters, similar looking characters and vowels have been removed */
		$possible = '23456789bcdfghjkmnpqrstvwxyz';
		$code = '';
		$i = 0;
		while ($i &lt; $characters) {
			$code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
			$i++;
		}
		return $code;
	}

	function CaptchaSecurityImages($width='120',$height='40',$characters='6') {
		$code = $this-&gt;generateCode($characters);
		/* font size will be 75% of the image height */
		$font_size = $height * 0.75;
		$image = @imagecreate($width, $height) or die('Cannot initialize new GD image stream');
		/* set the colours */
		$background_color = imagecolorallocate($image, 255, 255, 255);
		$text_color = imagecolorallocate($image, 51, 51, 51);
		$noise_color = imagecolorallocate($image, 110, 110, 110);
		/* generate random dots in background */
		for( $i=0; $i&lt;($width*$height)/10; $i++ ) {
			imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color);
		}
		/* generate random lines in background */
		for( $i=0; $i&lt;($width*$height)/150; $i++ ) {
			imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color);
		}
		/* create textbox and add text */
		$textbox = imagettfbbox($font_size, 0, $this-&gt;font, $code) or die('Error in imagettfbbox function');
		$x = ($width - $textbox[4])/2;
		$y = ($height - $textbox[5])/2;
		imagettftext($image, $font_size, 0, $x, $y, $text_color, $this-&gt;font , $code) or die('Error in imagettftext function');
		/* output captcha image to browser */
		header('Content-Type: image/jpeg');
		imagejpeg($image);
		imagedestroy($image);
		$_SESSION['security_code'] = $code;
	}

}

$width = isset($_GET['width']) ? $_GET['width'] : '120';
$height = isset($_GET['height']) ? $_GET['height'] : '40';
$characters = isset($_GET['characters']) &amp;&amp; $_GET['characters'] &gt; 1 ? $_GET['characters'] : '6';

$captcha = new CaptchaSecurityImages($width,$height,$characters);

?&gt;
</pre>
<p>Pentru un mai bun managment al codului este indicat ca scriptul PHP de deasupra DOCTYPE-ului, care valideaza datele introduse in formular si trimite emailul, sa se bage intr-un fisier include si sa fie apelat prin functia PHP include().</p>
<pre class="brush: php;">
&lt;?php @include('includes/send_email.inc.php'); ?&gt;
</pre>
<p>De asemenea, este indicat ca liniile CSS, care creeaza skinul formularului de contact, din sectiunea &lt;head&gt; &lt;/head&gt; sa fie bagate intr-un fisier CSS extern si apelate cu tagul HTML &lt;link /&gt;.</p>
<pre class="brush: xml;">
&lt;link href=&quot;css/contact_form_design.css&quot; type=&quot;text/css&quot; rel=&quot;stylesheet&quot; media=&quot;all&quot; /&gt;
</pre>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=Cum+fac+un+formular+de+contact%3F+http://wqoit.th8.us" title="Publica acest articol pe Twitter"><img class="nothumb" src="http://www.accesinterzis.ro/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=Cum+fac+un+formular+de+contact%3F+http://wqoit.th8.us" title="Publica acest articol pe Twitter">Publica acest articol pe Twitter</a></p>

<p><strong>Articole asemanatoare:<ul><li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-contact-versiunea-2/' rel='bookmark' title='Permanent Link: Cum fac un formular de contact? (versiunea 2)'>Cum fac un formular de contact? (versiunea 2)</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-comentarii/' rel='bookmark' title='Permanent Link: Cum fac un formular de comentarii?'>Cum fac un formular de comentarii?</a></li>
<li><a href='http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-inregistrare-a-utilizatorilor/' rel='bookmark' title='Permanent Link: Cum fac un formular de inregistrare a utilizatorilor?'>Cum fac un formular de inregistrare a utilizatorilor?</a></li>
</ul></p>]]></content:encoded>
			<wfw:commentRss>http://www.accesinterzis.ro/index.php/programare/cum-fac-un-formular-de-contact/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
