Encrypt password and log in PHP and PDO

Asked

Viewed 1,373 times

1

File login.php

    <?php

    session_start();

    require_once '../includes/config.php';

    if(isset($_REQUEST["post_back"])){

    $tb = $conn->prepare("select nm_usuario, imgPerfil, nome from usuario where nm_usuario=:usuario and senha_usuario=:senha");
    $tb->bindParam(":usuario", $_POST["usuario"], PDO::PARAM_STR);
    $tb->bindParam(":senha", $_POST["senha"], PDO::PARAM_STR);
    $tb->execute();
    $l = $tb->fetch(PDO::FETCH_ASSOC);
    $tb = null;
    if(!empty($l)){

    $_SESSION["usuario"] = $l["nm_usuario"]; // Pegar o Usuario logado
    $_SESSION["imgPerfil"] = $l["imgPerfil"]; // Pegar a imagem do perfil
    $_SESSION["nome"] = $l["nome"];           // Pegar o nome do Usuario logado
    header("Location: ../inicial.php");

    }else{

    echo("<script language = 'javascript'> alert('Usuario ou senha incorretos!'); </script>");
    echo("<script language = 'javascript'> location.href = '../index.php'; </script>");

    }

    }
    ?>

Below the file verifies.php

    <?php
    session_start();
    if(!isset($_SESSION["usuario"])){
    header("Location: index.php");
    exit;
    }
    ?>

Below the file exit.php

    <?php
    session_start();

    unset($_SESSION["usuario"]);
    unset($_SESSION["imgPerfil"]);
    unset($_SESSION["nome"]);
    session_destroy();

    header("Location: ../index.php");
    ?>

And below the file index.php where the login will be done:

    <?php
    session_start();
    if(isset($_SESSION["usuario"])){
    header("Location: inicial.php");
    exit;
    }
    ?>

    <html lang="pt_br">
    <head>
    <meta charset="utf-8" />
    <title>Painel de Controle - Portal WVD</title>
    <link rel="stylesheet" type="text/css" href="css/default.css" media="screen" />
    <script type="text/javascript" src="jquery-1.9.1.js"></script>
        </head>

        <body>

        <main id="login">
        <form id="form1" name="form1" method="post" action="acoes/login.php">
            <table>
        <tbody>
            <tr>
                <td colspan="2"><h1>Painel de Controle</h1></td>
            </tr>
        <tr>
            <td>Usuario:</td>
            <td><input type="text" name="usuario" id="user-name" /></td>
        </tr>

        <tr>
            <td>Senha:</td>
            <td><input type="password" name="senha" id="user-pass" /></td>
        </tr>

        <tr>
            v<td colspan="2"><input type="submit" name="post_back" id="user-login"                value="Iniciar Sessão" /></td>
        </tr>
        </tbody>
            </table>
    </form>

        </main>

</body>
    </html>

I wonder if this code is correct, if it has how to simplify and I would like to encrypt the password but I have no experience in which encryption to use.

1 answer

2


PHP already comes with some functions that can help you encrypt and decrypt. View documentation: MD5 and Crypt

However, it is always good to have a proper encryption algorithm. Ex:

<?php
class Hash {
private $hasBlowfish;
public function __construct() {
    self::$hasBlowfish = ( CRYPT_BLOWFISH === 1 ) ? TRUE : FALSE;
}
/**
 * Gera um 'salt' único de 22 chars para encriptar password
 * com o algoritmo blowfish.
 *
 * @return String - A unique salt string.
 */
public static function uniqueSalt() {
    return substr( sha1( mt_rand() ), 0, 22 );
}
/**
 * Cria um hash a partir de uma string/password.
 *
 * O hash é gerado com o algortitmo blowfish com um
 * custo 10.
 *
 * @return String - A blowfish, cost-10, hashed password.
 */
public static function hashPassword( $pass ) {
    // if ( ! self::$hasBlowfish ) {
    //     die( 'O servidor não suporta encriptação blowfish...' );
    // }
    return crypt( $pass, '$2a$10$' . self::uniqueSalt() );
}
/**
 * Verifica se um plain password é igual ao password
 * já hasheado. O password já hasheado vem do DB, por exemplo.
 *
 * @return Boolean TRUE if the passwords are the same, FALSE otherwise.
 */
public static function checkPasswords( $DbHashedPassword, $plainPassword ) {
    // Na verdade, nem precisa explicitamente pegar os primeiros 29 chars,
    // já que crypt() automaticamente descarta caracteres excedentes.
    $salt = substr( $DbHashedPassword, 0, 29 );
    $newHash = crypt( $plainPassword, $salt );
    return ( $DbHashedPassword == $newHash );
}
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.