The system will consist of a simple login, validated by user and password (encrypted) against a table in the database and storing the data in the session. There will be two levels of access for our users: normal (1) and administrator (2).
Creating the MySQL Table
You can execute this MySQL code to create our table of users that has 7 fields: id, name, user, password, levels, active and register:
CREATE TABLE IF NOT EXISTS 'usuarios' (
'id' INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
'nome' VARCHAR( 50 ) NOT NULL ,
'usuario' VARCHAR( 25 ) NOT NULL ,
'senha' VARCHAR( 40 ) NOT NULL ,
'email' VARCHAR( 100 ) NOT NULL ,
'nivel' INT(1) UNSIGNED NOT NULL DEFAULT '1',
'ativo' BOOL NOT NULL DEFAULT '1',
'cadastro' DATETIME NOT NULL ,
PRIMARY KEY ('id'),
UNIQUE KEY 'usuario' ('usuario'),
KEY 'nivel' ('nivel')
) ENGINE=MyISAM ;
With this you already have a table ready for our tutorial ... Run this script if you want to feed the table with some test users:
INSERT INTO 'usuarios' VALUES (NULL, 'Usuário Teste', 'demo', SHA1( 'demo' ), '[email protected]', 1, 1, NOW( ));
INSERT INTO 'usuarios' VALUES (NULL, 'Administrador Teste', 'admin', SHA1( 'admin' ), '[email protected]', 2, 1, NOW( ));
As you can see, our password field has 40 characters and when we register users we use
SHA1(‘{senha}’)
which means that we will use an encrypted password ... If you want to know more about sha1 see this article: Cryptography in PHP using md5 , sha1, and base64.
The XHTML Login Form
We will now create our form that will be where the visitor will enter the data and will be sent to the page validacao.php where the data will be validated (ohh).
<!-- Formulário de Login -->
<form action="validacao.php" method="post">
<fieldset>
<legend>Dados de Login</legend>
<label for="txUsuario">Usuário</label>
<input type="text" name="usuario" id="txUsuario" maxlength="25" />
<label for="txSenha">Senha</label>
<input type="password" name="senha" id="txSenha" />
<input type="submit" value="Entrar" />
</fieldset>
</form>
As this article is not a class on forms and POST method I will skip the part that talks about the names of these inputs and their relationship with PHP itself.
Validation of data
We already have the database and login form ... Now let's start validating. The following codes should be placed within the validation.php that will handle the data received form:
First of all we need to verify that the user actually filled in something on the form, otherwise we would send him back to index.php :
<?php
// Verifica se houve POST e se o usuário ou a senha é(são) vazio(s)
if (!empty($_POST) AND (empty($_POST['usuario']) OR empty($_POST['senha']))) {
header("Location: index.php"); exit;
}
?>
With this, any code that comes after that if will be sure that the data has been filled in the form.
Now we will open a connection to MySQL but this connection can be made in a different way, even before if you prefer ... After opening the connection we will transmit the two values entered by the visitor (user and password) to new variables and will use mysql_real_escape_string()
to avoid errors in MySQL.
<?php
// Verifica se houve POST e se o usuário ou a senha é(são) vazio(s)
if (!empty($_POST) AND (empty($_POST['usuario']) OR empty($_POST['senha']))) {
header("Location: index.php"); exit;
}
// Tenta se conectar ao servidor MySQL
mysql_connect('localhost', 'root', '') or trigger_error(mysql_error());
// Tenta se conectar a um banco de dados MySQL
mysql_select_db('usuarios') or trigger_error(mysql_error());
$usuario = mysql_real_escape_string($_POST['usuario']);
$senha = mysql_real_escape_string($_POST['senha']);
?>
Now it's time to validate the data against the user table:
<?php
// Verifica se houve POST e se o usuário ou a senha é(são) vazio(s)
if (!empty($_POST) AND (empty($_POST['usuario']) OR empty($_POST['senha']))) {
header("Location: index.php"); exit;
}
// Tenta se conectar ao servidor MySQL
mysql_connect('localhost', 'root', '') or trigger_error(mysql_error());
// Tenta se conectar a um banco de dados MySQL
mysql_select_db('usuarios') or trigger_error(mysql_error());
$usuario = mysql_real_escape_string($_POST['usuario']);
$senha = mysql_real_escape_string($_POST['senha']);
// Validação do usuário/senha digitados
$sql = "SELECT 'id', 'nome', 'nivel' FROM 'usuarios' WHERE ('usuario' = '". $usuario ."') AND ('senha' = '". sha1($senha) ."') AND ('ativo' = 1) LIMIT 1";
$query = mysql_query($sql);
if (mysql_num_rows($query) != 1) {
// Mensagem de erro quando os dados são inválidos e/ou o usuário não foi encontrado
echo "Login inválido!"; exit;
} else {
// Salva os dados encontados na variável $resultado
$resultado = mysql_fetch_assoc($query);
}
?>
Please note that we are looking for records that have the same user ID as the visitor entered and have a password equal to the SHA1 version of the password entered by the visitor. We also only look for user records that are active, so when you need to remove a user of the system, but can not simply delete the record, just change the value of the active column to zero. ;)
The generated query looks something like this:
SELECT 'id', 'nome', 'nivel' FROM 'usuarios' WHERE ('usuario' = 'a') AND ('senha' = 'e9d71f5ee7c92d6dc9e92ffdad17b8bd49418f98') AND ('ativo' = 1) LIMIT 1
After running query ( query ) we check whether the number of results found (or not) is different from one, if an error message is displayed, accompanied by exit
ends the script ... If it finds only one result we have our user and have already pulled your ID, name and access level of the database.
Saving the data in the session
Now we need to save the data found in the session because they will be used later in other pages and they need to "persist" by then ... After saving the data in the session we will redirect the visitor to a restricted page: p>
if (mysql_num_rows($query) != 1) {
// Mensagem de erro quando os dados são inválidos e/ou o usuário não foi encontrado
echo "Login inválido!"; exit;
} else {
// Salva os dados encontados na variável $resultado
$resultado = mysql_fetch_assoc($query);
// Se a sessão não existir, inicia uma
if (!isset($_SESSION)) session_start();
// Salva os dados encontrados na sessão
$_SESSION['UsuarioID'] = $resultado['id'];
$_SESSION['UsuarioNome'] = $resultado['nome'];
$_SESSION['UsuarioNivel'] = $resultado['nivel'];
// Redireciona o visitante
header("Location: restrito.php"); exit;
}
Checking if user is logged in
Our login system is almost complete! Now we just need to check if the user is logged into the system and if your access level matches that of the page ... Let's now write a small block of PHP at the beginning of the restrict.php file (which only must be accessed by logged in users):
<?php
// A sessão precisa ser iniciada em cada página diferente
if (!isset($_SESSION)) session_start();
// Verifica se não há a variável da sessão que identifica o usuário
if (!isset($_SESSION['UsuarioID'])) {
// Destrói a sessão por segurança
session_destroy();
// Redireciona o visitante de volta pro login
header("Location: index.php"); exit;
}
?>
<h1>Página restrita</h1>
<p>Olá, <?php echo $_SESSION['UsuarioNome']; ?>!</p>
Ready, my friend! Your login system is ready to go ... We're only going to make a few incremental steps to make it more "usable" ... Now you will see how to do the user verification logged in and access level, for example to a page where only administrators can have access:
<?php
// A sessão precisa ser iniciada em cada página diferente
if (!isset($_SESSION)) session_start();
$nivel_necessario = 2;
// Verifica se não há a variável da sessão que identifica o usuário
if (!isset($_SESSION['UsuarioID']) OR ($_SESSION['UsuarioNivel'] < $nivel_necessario)) {
// Destrói a sessão por segurança
session_destroy();
// Redireciona o visitante de volta pro login
header("Location: index.php"); exit;
}
?>
Logout Code
The file logout.php is so simple that it can have one line only:
<?php session_start(); session_destroy(); header("Location: index.php"); exit; ?>
Or if you prefer, a longer version:
<?php
session_start(); // Inicia a sessão
session_destroy(); // Destrói a sessão limpando todos os valores salvos
header("Location: index.php"); exit; // Redireciona o visitante
?>
Source: Thiago Belem