Correction exercices envoi d’e-mail en PHP : Série 02
Sommaire
Correction exercices envoi d’e-mail en PHP : Série 02
-
Exercice 01
-
Énoncé
- Vous pouvez visualiser l’énoncé de l’exercice
-
Solution
-
Page: connexion.php
-
Page: inscription.php
-
Page: fonctions.php
-
Page: login.php
-
Page: session.php
-
Page: accueil.php
-
Page: mot-de-passe-oublie.php
-
Page: reinitialisation-mot-de-passe.php
Voir la solution
<?php
$host = 'localhost';
$dbname = 'gestion-des-apprenants';
$user = 'root';
$passwd = '123';
try {
$pdo = new PDO("mysql:host=".$host.";dbname=".$dbname, $user, $passwd);
//echo "Connexion réalisée avec succès";
} catch (PDOException $e) {
print "Erreur !: " . $e->getMessage() . "<br/>";
die();
}
?>
Voir la solution
<?php
include('connexion.php');
include('fonctions.php');
if(isset($_POST['btnSubmit'])){
$userName = (isset($_POST['user-name'])) ? $_POST['user-name'] : null;
$userSurName = (isset($_POST['user-surname'])) ? $_POST['user-surname'] : null;
$userEmail = (isset($_POST['user-email'])) ? $_POST['user-email'] : null;
$userPassword = (isset($_POST['user-password'])) ? $_POST['user-password'] : null;
$userRepeatPassword = (isset($_POST['user-repeatpassword'])) ? $_POST['user-repeatpassword'] : null;
$userAgree = (isset($_POST['agree-term'])) ? $_POST['agree-term'] : null;
if(!empty($userName)&&!empty($userSurName)&&!empty($userEmail)&&!empty($userPassword)&&!empty($userRepeatPassword)&&!empty($userAgree)){
if (check_mdp_format($userPassword) === true){
if($userPassword===$userRepeatPassword){
//Rechercher l'existance d'email dans la table
/*$stmt = $pdo->prepare("SELECT * FROM utilisateurs WHERE emailUtilisateur=?");
$stmt->execute([$userEmail]);
$user = $stmt->fetch();
echo 'ggg '.$user;*/
if (chercher_email($userEmail,'emailUtilisateur')===false) {
//hasher le mot de passe
$userPasswordHash = password_hash( $userPassword, PASSWORD_DEFAULT);
echo $userPasswordHash;
try {
$sql = "INSERT INTO utilisateurs (nomUtilisateur, prenomUtilisateur,emailUtilisateur,passwordUtilisateur )
VALUES (?,?, ?, ?)";
$stmt=$pdo->prepare($sql);
$exec = $stmt->execute(array($userName,$userSurName,$userEmail,$userPasswordHash));
echo '<script type="text/javascript">alert("Données enregistrées avec succès"); </script>';
header("Location: login.php");
} catch(PDOException $e) {
echo $e->getMessage();
}
}else{echo '<script type="text/javascript">alert("L\'email existe déjà"); </script>';}
}else{echo '<script type="text/javascript">alert("Mot de passes différents"); </script>';}
}else{echo '<script type="text/javascript">alert("Mot de passes invalide"); </script>';}
}else{echo '<script type="text/javascript">alert("Remplir tous les champs"); </script>';}
}
//Sélection des gouvernorats
$gouv = "select cdegouvernorat,intituleFr from gouvernorats";
$stmt = $pdo->prepare($gouv);
$stmt->execute();
$gouvListe = $stmt->fetchall();
//Sélection des groupes
$group = "select cdegroupe,intitulegr from groupes";
$stmt = $pdo->prepare($group);
$stmt->execute();
$groupListe = $stmt->fetchall();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Sign Up Form by Colorlib</title>
<!-- Font Icon -->
<link rel="stylesheet" href="fonts/material-icon/css/material-design-iconic-font.min.css">
<!-- Main css -->
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="main">
<section class="signup">
<!-- <img src="images/signup-bg.jpg" alt=""> -->
<div class="container">
<div class="signup-content">
<form method="POST" id="signup-form" class="signup-form">
<h2 class="form-title">Créer un compte </h2>
<div class="form-group">
<input type="text" class="form-input" name="user-name" id="name" placeholder="Votre nom"
value='<?php if(isset($_POST['btnSubmit'])){if(!empty($userName)){echo $userName; } } ?>'/>
</div>
<div class="form-group">
<input type="text" class="form-input" name="user-surname" id="surname" placeholder="Votre prénom"/>
</div>
<div class="form-group">
<input type="email" class="form-input" name="user-email" id="email" placeholder="Votr Email"/>
</div>
<div class="form-group">
<input type="text" class="form-input" name="user-password" id="password" placeholder="Votre Password"/>
<span toggle="#password" class="zmdi zmdi-eye field-icon toggle-password"></span>
</div>
<div class="form-group">
<input type="password" class="form-input" name="user-repeatpassword" id="re_password" placeholder="Répétez votre mot de passe"/>
</div>
<div class="form-group">
<input type="checkbox" name="agree-term" id="agree-term" class="agree-term" />
<label for="agree-term" class="label-agree-term"><span><span></span></span>Je suis d'accord avec toutes les déclarations.<a href="#" class="term-service"> Conditions d'utilisation</a></label>
</div>
<div class="form-group">
<input type="submit" name="btnSubmit" id="submit" class="form-submit" value="S'inscrire"/>
</div>
</form>
<p class="loginhere">
Vous avez déjà un compte ? <a href="login.php" class="loginhere-link">Connectez-vous</a>
</p>
</div>
</div>
</section>
</div>
<!-- JS -->
<script src="vendor/jquery/jquery.min.js"></script>
<script src="js/main.js"></script>
</body><!-- This templates was made by Colorlib (https://colorlib.com) -->
</html>
Voir la solution
<?php
//session_start();
function check_mdp_format($mdp)
{
$majuscule = preg_match('@[A-Z]@', $mdp);
$minuscule = preg_match('@[a-z]@', $mdp);
$chiffre = preg_match('@[0-9]@', $mdp);
if(!$majuscule || !$minuscule || !$chiffre || strlen($mdp) < 8)
{
return false;
}
else
return true;
}
function chercher_email($mail,$champs){
include('connexion.php');
$stmt = $pdo->prepare("SELECT * FROM utilisateurs WHERE ".$champs."=?");
$stmt->execute([$mail]);
$user = $stmt->fetch();
//echo 'ggg '.$user;
if ($user) {
return true;
}else{
return false;
}
}
function chercher_passward($passward,$userEmail, $champs){
include('connexion.php');
//"SELECT `passwordUtilisateur` FROM `utilisateurs` WHERE `emailUtilisateur`='hajjriadh@gmail.com'
$stmt = $pdo->prepare("SELECT nomUtilisateur,prenomUtilisateur,passwordUtilisateur FROM utilisateurs WHERE ".$champs."=?");
$stmt->execute([$userEmail]);
$hash = $stmt->fetch();
if (password_verify($passward, $hash[2])) {
$_SESSION['utilisateur']=$hash[0]." ".$hash[1];
return true;
}else{
return false;
}
}?>
Voir la solution
<?php
session_start();
include('connexion.php');
include('fonctions.php');
if(isset($_POST['btnSubmit'])){
$userEmail = (isset($_POST['user-email'])) ? $_POST['user-email'] : null;
$userPassword = (isset($_POST['user-password'])) ? $_POST['user-password'] : null;
if(!empty($userEmail)&&!empty($userPassword)){
if (chercher_email($userEmail,'emailUtilisateur')===true) {
if (chercher_passward($userPassword, $userEmail,'emailUtilisateur')===true) {
//echo $_SESSION['utilisateur'];
header("Location: session.php");
}else{echo '<script type="text/javascript">alert("Le mot de passe est invalide."); </script>';}
}else{echo '<script type="text/javascript">alert("L\'email n\'existe pas"); </script>';}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Sign Up Form by Colorlib</title>
<!-- Font Icon -->
<link rel="stylesheet" href="fonts/material-icon/css/material-design-iconic-font.min.css">
<!-- Main css -->
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="main">
<section class="signup">
<!-- <img src="images/signup-bg.jpg" alt=""> -->
<div class="container">
<div class="signup-content">
<form method="POST" id="signup-form" class="signup-form">
<h2 class="form-title">Se connecter</h2>
<div class="form-group">
<input type="email" class="form-input" name="user-email" id="email" placeholder="Votr Email"/>
</div>
<div class="form-group">
<input type="text" class="form-input" name="user-password" id="password" placeholder="Votre Password"/>
<span toggle="#password" class="zmdi zmdi-eye field-icon toggle-password"></span>
</div>
<div class="form-group">
<input type="submit" name="btnSubmit" id="submit" class="form-submit" value="Se connecter"/>
</div>
</form>
<p class="loginhere">
Vous avez oublié ? <a href="mot-de-passe-oublie.php" class="loginhere-link">Mot de passe</a>
</p>
</div>
</div>
</section>
</div>
<!-- JS -->
<script src="vendor/jquery/jquery.min.js"></script>
<script src="js/main.js"></script>
</body><!-- This templates was made by Colorlib (https://colorlib.com) -->
</html>
Voir la solution
<?php
session_start();
include('connexion.php');
include('fonctions.php');
if(!isset($_SESSION['utilisateur']))
{
session_destroy();
//rediriger l'utilisateur vers la page d'accueil
header("Location: login.php");
// On n'affiche plus rien
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Sign Up Form by Colorlib</title>
<!-- Font Icon
<link rel="stylesheet" href="fonts/material-icon/css/material-design-iconic-font.min.css">-->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<!-- Main css
<link rel="stylesheet" href="css/style.css">-->
<body>
<!-- Navbar -->
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Dropdown
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="#">Action</a></li>
<li><a class="dropdown-item" href="#">Another action</a></li>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" href="#">Something else here</a></li>
</ul>
</li>
<li class="nav-item">
<a class="nav-link disabled">Disabled</a>
</li>
</ul>
<div class="d-flex">
<p>Bienvenue :
<?php echo $_SESSION['utilisateur'];?></p><a href='accueil.php'> Déconnection</a>
</div>
</div>
</div>
</nav>
</head><h1>Bienvenue <?php echo $_SESSION['utilisateur'];?></h1>
<!-- JS
<script src="vendor/jquery/jquery.min.js"></script>
<script src="js/main.js"></script>-->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body><!-- This templates was made by Colorlib (https://colorlib.com) -->
</html>
Voir la solution
<?php
session_start();
include('connexion.php');
include('fonctions.php');
//session_start();
session_destroy();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Sign Up Form by Colorlib</title>
<!-- Font Icon
<link rel="stylesheet" href="fonts/material-icon/css/material-design-iconic-font.min.css">-->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<!-- Main css
<link rel="stylesheet" href="css/style.css">-->
<body>
<!-- Navbar -->
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Dropdown
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="#">Action</a></li>
<li><a class="dropdown-item" href="#">Another action</a></li>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" href="#">Something else here</a></li>
</ul>
</li>
<li class="nav-item">
<a class="nav-link disabled">Disabled</a>
</li>
</ul>
<div class="d-flex">
<div class="btn-group">
<a href="inscription.php" class="btn btn-warning">Créer un compte </a>
<a href="login.php" class="btn btn-success">Se connecter</a>
</div>
</div>
</div>
</div>
</nav>
<div class="d-flex justify-content-center">
<div class="alert alert-primary w-30 " role="alert" >
Vous n'avez pas encore de compte ? <a href="inscription.php">Inscrivez-vous</a> maintenant!
</div>
</div>
<!-- JS
<script src="vendor/jquery/jquery.min.js"></script>
<script src="js/main.js"></script>-->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body><!-- This templates was made by Colorlib (https://colorlib.com) -->
</html>
Voir la solution
<?php
session_start();
include('connexion.php');
include('fonctions.php');
if(isset($_POST['btnSubmit'])){
$userEmail = (isset($_POST['user-email'])) ? $_POST['user-email'] : null;
if(!empty($userEmail)){
if (chercher_email($userEmail,'emailUtilisateur')===true) {
//On génère un token
$string=implode('',array_merge(range('A','Z'),range('a','z'),range('0','9')));
$token = substr(str_shuffle($string),0,20);
//On insère la date et le token dans la BD
$stmt = $pdo->prepare('update utilisateurs set date_recuperation_mot_passe=now(),
token_recuperation_mot_passe=? where emailUtilisateur = ?');
$exec = $stmt->execute(array($token,$userEmail));
//On prépare l'envoie du courrier
$link='http://127.0.0.1/php/authentification/cryptermotpasse/inscription/reinitialisation-mot-de-passe.php?token='.$token;
$to='apcpedagogie1@gmail.com';
$sujet='Rénitialisation de votre mot de passe';
$message='<h1>Réinitialisation de votre mot de passe</h1>
<p>Pour rénitialiser votre mot de passe, veuillez suivre ce lien : <a href="'.$link.'">'.$link.'</a></p>';
//On défini les entêtes requis
$header = [];
$header[]='From: apcpedagogie1@gmail.com';
$header[]='MIME-Version: 1.0';
$header[]='Content-Type: text/html; charset=utf-8';
$header[]='To: '.$to.' <'.$to.'>';
//On envoie le courrier
if(mail($to,$sujet,$message, implode("\r\n",$header))){
echo '<script type="text/javascript">alert("Email envoyé avec succès à $to ...");</script>';
} else {
echo '<script type="text/javascript">alert("Échec de l\'envoi de l\'email...");</script>';
}
/*$message='<div style="color:green;"> Un courrier à été acheminé.
Veuillez regarder votre boîte aux lettres et suivre les instructions à
l\'interieur du courrier.</div>';*/
//echo 'gfgfgfgfg'.$to.$sujet.$message;
//echo '<script type="text/javascript">alert("Un courrier à été acheminé"); </script>';
}else{echo '<script type="text/javascript">alert("L\'email n\'existe pas"); </script>';}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Sign Up Form by Colorlib</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<!-- Main css -->
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="main">
<section class="signup">
<!-- <img src="images/signup-bg.jpg" alt=""> -->
<div class="container">
<div class="signup-content">
<form method="POST" id="oublie-form" class="signup-form">
<h2 class="form-title">Rénitialiser votre mot de passe</h2>
<div class="form-group">
<input type="email" class="form-input" name="user-email" id="email" placeholder="Votr Email"/>
</div>
<div class="form-group">
<input type="submit" name="btnSubmit" id="submit" class="form-submit" value="Envoyez-moi un mot de passe aléatoire"/>
</div>
</form>
<p class="loginhere">
Vous avez oublié ? <a href="login.php" class="loginhere-link">Retour</a>
</p>
</div>
</div>
</section>
</div>
<!-- JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body>
</html>
Voir la solution
<?php
session_start();
include('connexion.php');
include('fonctions.php');
// Variable utilisé pour afficher une notification d'erreur ou de succès
$msg = '';
if (empty($_GET['token'])) { // Si aucun token n'est spécifié en paramètre de l'URL
echo 'Aucun token n\'a été spécifié';
exit;
}
// On récupère les informations par rapport au token dans la base de données
$stmt = $pdo->prepare('SELECT date_recuperation_mot_passe FROM utilisateurs WHERE token_recuperation_mot_passe = ?');
$stmt->bindValue(1, $_GET['token']);
$stmt->execute();
$ligne = $stmt->fetch(PDO::FETCH_ASSOC);
if (empty($ligne)) { // Si aucune info associée au token n'est trouvé
echo 'Ce token n\'a pas été trouvé';
exit;
}
// On calcul la date de la génération du token + 15minutes
$dateToken = strtotime('+15 minutes', strtotime($ligne['date_recuperation_mot_passe']));
$DateAujourdhui = time();
if ($dateToken < $DateAujourdhui) { // Si la date est dépassé le délais de 3hrs
echo 'Token expiré !';
exit;
}
if (!empty($_POST)) { // Si le formulaire a été soumis
if (!empty($_POST['password']) && !empty($_POST['password_confirm'])) { // Si le formulaire est correctement remplit
if ($_POST['password'] === $_POST['password_confirm']) { // Si les deux mots de passes sont les mêmes
// On hash le mot de passe
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$token = $_GET['token'];
// On modifie les informations dans la base de données
$query = $pdo->prepare('UPDATE utilisateurs SET passwordUtilisateur = ?, token_recuperation_mot_passe = "" WHERE token_recuperation_mot_passe = ?');
$exec = $query->execute(array($password, $token));
header("Location: login.php");
echo '<script type="text/javascript">alert("Le mot de passe a été changé avec succès!"); </script>';
} else { // si les deux mots de passe ne sont pas identiques
$msg = '<div style="color: red;">Les deux mots de passes ne sont pas identiques.</div>';
}
} else {
$msg = '<div style="color: red;">Veuillez remplir tous les champs du formulaire.</div>';
}
}
?>
<?php echo $msg; ?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Rénitialiser votre mot de passe</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<!-- Main css -->
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="main">
<section class="signup">
<!-- <img src="images/signup-bg.jpg" alt=""> -->
<div class="container">
<div class="signup-content">
<form method="POST" id="oublie-form" class="signup-form">
<h2 class="form-title">Rénitialiser votre mot de passe</h2>
<div class="form-group">
<input type="password" class="form-input" name="password" id="email" placeholder="password"/>
</div>
<div class="form-group">
<input type="password" class="form-input" name="password_confirm" id="email" placeholder="password_confirm"/>
</div>
<div class="form-group">
<input type="submit" name="btnSubmit" id="submit" class="form-submit" value="Changer le mot de passe"/>
</div>
</form>
</div>
</div>
</section>
</div>
<!--
<form action="reinitialisation-mot-de-passe.php?token=<?php echo $_GET['token']; ?>" method="post">
<label>Mot de passe : <input type="password" name="password" value="" /></label><br />
<label>Confirmation du mot de passe : <input type="password" name="password_confirm" value="" /></label><br />
<button type="submit">Changer le mot de passe</button>-->
<!-- JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body>
</html>