Sécuriser des mots de passe en PHP (password_hash & password_verify)

PrimFX Boris ('PrimFX') Le 23 janvier 2022

Depuis sa version 5.5, PHP intègre un ensemble de fonctions permettant de hacher et vérifier le hash de mots de passe. Dans cette vidéo, je vous propose de découvrir comment stocker les mots de passe de vos utilisateurs de façon sécurisée avec les fonctions PHP password_hash() et password_verify().

Ressources utiles :

Code du tuto :

  • Création de la table "users" en SQL :
CREATE TABLE users (id int primary key auto_increment, email varchar(255) not null, password varchar(255) not null, createdAt datetime not null default NOW());
  • index.php
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Inscription/Connexion</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

    <form method="POST" action="register.php">
        <input type="email" placeholder="Email" name="email"><br>
        <input type="password" placeholder="Mot de passe" name="password"><br>
        <button type="submit">Inscription</button>
    </form>

    <hr>

    <form method="POST" action="login.php">
        <input type="email" placeholder="Email" name="email"><br>
        <input type="password" placeholder="Mot de passe" name="password"><br>
        <button type="submit">Connexion</button>
    </form>
    
</body>
</html>
  • register.php
<?php
require('./db.php');

if (!empty($_POST['email']) && !empty($_POST['password'])) {
    $email = $_POST['email'];
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);

    var_dump($email);
    var_dump($password);

    $q = $db->prepare('INSERT INTO users (email, password) VALUES (:email, :password)');
    $q->bindValue('email', $email);
    $q->bindValue('password', $password);
    $res = $q->execute();

    if ($res) {
        echo "Inscription réussie";
    }
}
  • login.php
<?php
require('./db.php');

if (!empty($_POST['email']) && !empty($_POST['password'])) {
    $email = $_POST['email'];
    $password = $_POST['password'];

    var_dump($email);
    var_dump($password);

    $q = $db->prepare('SELECT * FROM users WHERE email = :email');
    $q->bindValue('email', $email);
    $q->execute();
    $res = $q->fetch(PDO::FETCH_ASSOC);
    
    var_dump($res);
    
    if ($res) {
        $passwordHash = $res['password'];
        if (password_verify($password, $passwordHash)) {
            echo "Connexion réussie !";
        } else {
            echo "Identifiants invalides";
        }
    } else {
        echo "Identifiants invalides";
    }
}

 


A propos de l'auteur

PrimFX
Boris ('PrimFX')

Je m'appelle Boris, j'ai 22 ans et je suis passionné d'informatique. Suite à mes études (Licence Informatique puis MSc Computer Science au Trinity College Dublin), je gère l'entreprise Single Quote co-fondée en 2019 et je profite de mon temps libre pour partager ma passion à travers des vidéos & articles 😃

Votre commentaire

Vous devez être connecté pour poster un commentaire. Se connecter ou Créer un compte

Commentaires 2

  • tutherchaar Le 29 février, à 08:49 | Répondre

    FACE TO FACE DEAL @SOUTH AMERICA BUY SSD-CHEMICALS-SOLUTIONS FOR All BANK NOTES AND LABORATOIRES CHEMICALS, RED AND SILVER MERCURY (( +16265140391   )) in United states of America,Canada,England,France,South Africa,Dubai,Qatar,Sweden,Germany,Italy,Chile,Kuwa iti,Spain,Netherlands,Poland,Ecuador,New Zealand,Scotland,Brazil,Malta,Norway,Jamaica,Latvi a,Russia,Jordan,Oman,Saudi-Arabia,Turkey,Dubai,Afghanistan,Denmark,Argentina, Mauritius,Iraq,Iran,Egypt,Botswana,Malawi,Switzerl and,Swaziland,Lesotho,Georgia,Hawaii,Ghana,Angola, Zimbabwe,Philippines,Hong Kong,Uganda,China,Japan and allover The World.As one of the fastest growing money cleaning company in world, we offer smart SSD solutions and as our company is still growing and innovating. Running successfully from Last 10 years with Indian and Foreign experts with State Of the Art labs and machines. We offer the Cheapest Chemicals on% Bases All Over the World. We have a variety of SSD chemicals that can clean out your deface Notes perfectly, Black Note, Red Notes, Green Notes, Stained Notes, Stamped Notes & Also Coded Notes. We also Melt Frozen Chemicals in our dispensary and our services are professional and Genuine. We lease out cleaning machines worldwide and we can work on commission basis. Expert Agents Available to travel worldwide. Our 3D laser automatic black money cleaning machine is available for rent / hire / sales to perform any defaced blackened money cleaning both local and international. We’ll travel our expert technician with this machine to your country anywhere. Activation powder refers to a reactivation member of the SSD chemical products which is been pour and rob all overamaged notes; bills like USD and blacks EURO, POUNDS, transferring colors from us ded note to new white bills. Please inform us immediately on whatsapp: (( +  16265140391   )) or Email: (( chemicalsmercury435@gmail.com))We can come in your country like Zambia, Zimbabwe, Botswana, Swaziland, Lesotho, Malawi, Kenya, Uganda, Afghanistan, Namibia and Cities like Limpopo, Free State, Durban, Cape, Town, Pietermaritzburg, Sasolburg, Mpumalanga, Secunda, Standerton, Middelburg, Carltonville, Potchefstrom, Johannesburg, Eastern Cape, Western, Cape, Gauteng, Welkom, Orkney, Pretoria, Tzaneen, Swellendam, Robertson, Montagu, Paarl, Klaapmut, George, Giyani, Rustenburg , Nelspruit, Soweto, Krugersdorp, Boksburg, Vanderbijlpark, Vereenining, Bloemfontein, Newcastle, Sashanguve, New York, Harare, Bulawayo, Burdersfort, Thohoyandou, Roodeport, Mayfair, Botswana. Please inform us immediately on Email: chemicalsmercury435@gmail.com      H arare, Bulawayo, Burdersfort, Thohoyandou, Roodeport, Mayfair, Botswana. Please inform us immediately on Or whatsapp ( + 16265140391     )). Harare, Bulawayo, Burdersfort, Thohoyandou, Roodeport, Mayfair, Botswana.Please inform us immediately on Email: (( chemicalsmercury435@gmail.com    )) 

  • totoro Le 1 avril, à 02:50 | Répondre

    Super, tu reprends les tutos php?
    C'est super !

    merci chef