ACCES INTERZIS | blog de programare si securitate IT


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 este personalizat pentru fiecare eroare in parte
  • campurile care contin date invalide sunt evidentiate
  • scriptul pastreaza datele introduse in campurile formularului atunci cand detecteaza o eroare
  • designul formularului este creat EXCLUSIV din CSS
  • de protectie antispam nu avem nevoie deoarece se presupune ca formularul de inregistrare se afla in interiorul unei sectiuni de administrare

Asadar, ca sa realizez un formular de inregistrare a utilizatorilor mai intai creez in baza de date tabelul care va stoca toti utilizatorii.

$q = "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))";

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

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

<?php
/*
Titlu: Cum fac un formular de 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 && $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 <strong>username</strong>.';
	} else {
		$post['username'] = trim($_POST['username']);

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

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

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

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

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

		if (strlen($post['email']) < 3) {
			$errors['email'] = 'The <strong>email address</strong> is too short.';
		} else {
			if (strlen($post['email']) > 30) {
				$errors['email'] = 'The <strong>email address</strong> is too long.';
			} else {
				if (!preg_match('/^[a-z0-9][a-z0-9_.]+@[a-z0-9-.]+\.[a-z]{2,4}$/i', $post['email'])) {
					$errors['email'] = 'The <strong>email address</strong> isn\'t valid.';
				} else {
					$q = "SELECT user_id FROM ai_registrationform WHERE LOWER(email)='".strtolower($post['email'])."'";
                    $result = mysql_query($q) or die(mysql_error());

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

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

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

		if (strlen($post['password']) < 5) {
			$errors['password'] = 'The <strong>password</strong> is too short.';
		} else {
			if (strlen($post['password']) > 30) {
				$errors['password'] = 'The <strong>password</strong> is too long.';
			} else {
				if (!preg_match('/^[a-z0-9][a-z0-9_ ]*[a-z0-9]$/i', $post['password'])) {
					$errors['password'] = 'The <strong>password</strong> 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 => $v) {
			$post[$k] = mysql_real_escape_string($v);
		}

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

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

		$confirmation .= ' <a href="http://'.$_SERVER['HTTP_HOST'].$php_self.'" title="Back" id="back">Back to registration form</a>';

		$display = 'style="display:none;"';
	}

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

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

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

/*INCEPUT - LINIILE CSS CARE CREEAZA SKINUL FORMULARULUI DE 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*/
</style>
</head>

<body>
<div id="registrationf">
	<h1>
		<label>&nbsp;</label>
		Register an user
	</h1>

	<?php if (isset($confirmation)) echo '<p>'.$confirmation.'</p>'; ?>

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

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

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

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

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

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().

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

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

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

Post to Twitter Publica acest articol pe Twitter

Articole asemanatoare:

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

Etichete
Etichete: , , ,
Categorii: programare


 

Comentarii lasate » (3 Total)

 
  1. x6IT32 says:

    Felicitari pt. toate tutorialele, mult respect!

  2. bvlucretiu says:

    Am incercat toate variantele dar i-mi da: ” Access denied for user ‘ODBC’@'localhost’ (using password: NO) ”
    Nu stiu ce nu am facut bine?

  3. bvlucretiu says:

    Sunt incepator in programare dar cat de cat informat astfel incat sa-mi pot crea un SIT in PHP insa am incercat sa inteleg lucrul cu baza de date dar nu stiu de unde sa incep;
    Am un sit personal creat in serverul local si incerc sa inteleg cum functioneaza dar tot unele lucruri i-mi scapa… cand incerc sa ma conectaez la baza de date i-mi da “Access denied for user ‘ODBC’@'localhost’ (using password: NO)”

Lasa un comentariu

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