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 run this Mysql code to create our user table 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 test users we use SHA1(‘{senha}’)
this means that we will use an encrypted password... If you want to know more about sha1 see this article: PHP encryption using md5, sha1 and Base64.
The XHTML Login form
We will now create our form which will be where the visitor will enter the data and will be sent to the validation.php page 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.
The validation of the data
We already have the database and the login form... Now we will start to do the validation. The next codes should be placed within the.php validation that will handle the data received from the form:
First of all we need to check if the user actually filled something in the form, otherwise we send it back to the 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 this if will be sure that the data were filled in the form.
Now we will open a connection with Mysql but this connection can be done otherwise, 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 use the 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);
}
?>
Note that we are searching for records that have the user as typed by the visitor and that have a password equal to the SHA1 version of the password typed by the visitor... We also only search for user records that are active, so when you need to remove a user from the system, but you can’t just delete the record by just changing the value of the active column to zero. ;)
The generated query looks like this:
SELECT `id`, `nome`, `nivel` FROM `usuarios` WHERE (`usuario` = 'a') AND (`senha` = 'e9d71f5ee7c92d6dc9e92ffdad17b8bd49418f98') AND (`ativo` = 1) LIMIT 1
After rotating the query (query) we check if the number of results found (or not) is different from one, if it is displayed an error message accompanied by a exit
which finalizes the script... If it finds only one result we have our user and we have already pulled your ID, name and access level from the database.
Saving the data in session
Now we need to save the data found in the session because they will be used later on other pages and they need to "persist" there... After saving the data in the session we will redirect the visitor to a restricted page:
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 the user is logged in
Our system of login is almost complete! Now we just need to check if the user is logged in to the system and if your level of access matches that of the page... Let’s now write a small PHP block at the beginning of the file restricted.php (that should only 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 work... Let’s just make a few increments to make it more "usable"... Now you will see how to check logged in user and access level, for example for a page where only administrators can 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 archive logout.php is so simple that you can have one line:
<?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
Ziad.ali is here one of several ways to do this. Good studies.
– KaduAmaral
@Ziad.ali just to not let you down I suggest reading these topics: Creating access control with PHP and Mysql and How to create a Login System with Permission Levels
– RodrigoBorth
@Kaduamaral The question is reopened. Ziad, even then it would be cool if you [Dit] the question is to add more information, as if your system already has user registration, if you consider user groups, if the login and authentication part already exists and how it was implemented, what database used, etc.
– bfavaretto
Since the question is old, the answer will be new... The way forward would be to use PHP with Laravel Framework, search something on the net like Laravel ACL. Check out this video : https://www.youtube.com/watch?v=hJRt0BDF0Do
– user39458