Avez-vous une question? (216) 97 656 803 hajjriadh@gmail.com
PHP

Correction exercices envoi d'e-mail en PHP : Série 01

Un cours complet pour maîtriser Correction exercices envoi d'e-mail en PHP : Série 01.

0 chapitres 0 QCM Accès gratuit
  1. Objectifs

  2. Exercice 01

    1. Énoncé
    2. Solution
      <!doctype html>
      <html lang="fr">
        <head>
          <!-- Required meta tags -->
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      
          <!-- Bootstrap CSS -->
          <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
      
          <title>Votre commande</title>
          <style>
      fieldset {
      			border: 2px solid #dcdcdc;
      			border-radius: 10px;
      			padding: 10px 20px;
      			text-align: leftt;
            width:50%;
      		}
          legend {
      		width:50%;
      		}    
      </style>
        </head>
        <body>
      <div class="container">
      </br>
      <div><h3>Liste des articles en stock</h3> "HTML 5" : 30.900<br />"CSS 3" : 14.100 <br />"PHP 7" :
      29.500 <br />"MySQL" : 19.750 <br /><br /></div>
      <form class="form-inline" action="<?= $_SERVER['PHP_SELF'] ?> " method="post" enctype="application/x-www-form-urlencoded" >
      <fieldset>
      <legend>Passez votre commande</legend>
      <div class="row mb-2">
             <div class="col-lg-4 ">
                <label for="ex1" >Article</label>
              </div>
              <div class="col-lg-8">
                <input type="text" type="text" name="article" class="form-control" size="60"/>
              </div>
        </div>
      <div class="row mb-2">
              <div class="col-lg-4">
                <label for="ex1" >Quantité</label>
              </div>
              <div class="col-lg-8">
                <input type="text" name="quantite" class="form-control" size="60"/>
              </div>
        </div>
      <div class="row mb-2">
              <div class="col-lg-4">
                <label for="ex1" >Prénom & Nom</label>
              </div>
              <div class="col-lg-8">
                <input type="text" name="nom" class="form-control" size="60"/>
              </div>
      </div>
      <div class="row mb-2">  
              <div class="col-lg-4">
                <label for="ex1" >Adresse</label>
              </div>
              <div class="col-lg-8">
                <input type="text" name="adresse" class="form-control" size="60"/>
              </div>
      </div>
      <div class="row mb-2">
              <div class="col-lg-4">
                <label for="ex1" >E-mail</label>
              </div>
              <div class="col-lg-8">
                <input type="text" name="mail" class="form-control" size="60"/>
              </div>
      </div>
      <div class="row mb-2">
      <div class="col-lg-6">
        <button type="reset" class="btn btn-primary mb-2 w-100" name="effacer">Effacer</button>
        </div>
        <div class="col-lg-6">
        <button type="submit" class="btn btn-primary mb-2 w-100" name="envoi">Envoyer</button>
         </div>
      </div>
      </fieldset>
      </form>
      <!-- SCRIPT PHP -->
      <?php
      //******************************
      // Création du tarif des livres
      $tarif= array("HTML 5"=>30.900,"CSS 3"=>14.100,"PHP 7"=>29.500,"MySQL"=>19.750);
      // Gestion de la commande
      if(isset($_POST['article'])&& isset($_POST['quantite']) && isset($_POST['nom'])
      && isset($_POST['adresse']) && isset($_POST['mail']) )
      {
      $article=$_POST['article'];
      $prix= $tarif[$article];
      $objet="Confirmation de commande";
      // Contenu de l’e-mail
      $text= "Nous avons bien reçu votre commande de : \n";
      $text.="{$_POST['quantite']} livres ";
      $text.= $_POST['article'] . " au prix unitaire de : ". number_format($prix, 3) ." Dinars \n";
      $text.= "Soit un prix total de : ".number_format($prix * $_POST['quantite'],3)." Dinars \n";
      $text.="Adresse de livraison : \n". $_POST['nom']. " \n";
      $text.=$_POST['adresse']. " \n";
      $text .=" Cordialement";
      if(mail($_POST['mail'],$objet,$text))
      {
      echo "<h3>Vous allez recevoir un e-mail de confirmation</ h3>";
      }
      else
      {
      echo "<h3>L'e-mail n'a pas été envoyé : recommencez ! </h3>";
      }
      } ?>
      <!-- Optional JavaScript -->
          <!-- jQuery first, then Popper.js, then Bootstrap JS -->
          <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
          <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
          <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
        </body>
      </html>
      
  3. Exercice 02

    1. Énoncé
    2. Solution
      1. commentaire html
        <!doctype html>
        <html lang="fr">
          <head>
            <!-- Required meta tags -->
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        
            <!-- Bootstrap CSS -->
            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
        
            <title>Formulaire de commentaires simple</title>
            <style>
        fieldset {
        			border: 2px solid #dcdcdc;
        			border-radius: 10px;
        			padding: 10px 20px;
        			text-align: leftt;
              width:60%;
        		}
            legend {
        		width:50%;
        		}    
        </style>
          </head>
          <body>
        <div class="container">
        
        <form action = "exemple.php" method = "post">
            <fieldset>
                <legend>Ajouter un commentaire</legend>
        <div class="row mb-2">
                    <div class="col-lg-4">
                      <label for="ex1" >Adresse e-mail</label>
                    </div>
                    <div class="col-lg-8">
                      <input type="text" name="email_address" class="form-control" size="40"/>
                    </div>
        </div>
        
        <div class="row mb-2">
            <div class="col-lg-4">
              <label for="ex1" >Votre commentaire</label>
            </div>
            <div class="col-lg-8">
                <textarea type="text" name="feedback" class="form-control" cols = "50" rows = "10"></textarea>
            </div>
        </div>
        
        
        <button type="submit" class="btn btn-primary mb-2 w-100" name="send">Soumettre</button>
        
        
        </fieldset>
        </form>
        </div>
        <!-- Optional JavaScript -->
            <!-- jQuery first, then Popper.js, then Bootstrap JS -->
            <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
            <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
          </body>
        </html>
        
      2. commentaire html
        <?php
        
        #Receive user input
        $email_address = $_POST['email_address'];
        $feedback = $_POST ['feedback'];
        $envoye=false;
        //Entrée utilisateur #Filter
        function filter_email_header ($form_field) { global $envoye;
          $envoye=true;  
        return filter_var($form_field, FILTER_SANITIZE_EMAIL);
        }
        
        $email_address = filter_email_header($email_address);
        
        
        
        #Merci à l'utilisateur ou informez-le d'un problème
        if ($envoye==true) {
        
        
        #Envoyer un e-mail
        $headers = "De: $email_address";
        $sent = mail ('hajjriadh@gmail.com ',' Soumission du formulaire de commentaires ', $feedback, $headers);
        ?>
        <html>
        <head>
        <title> Merci </title>
        </head>
        <body>
        <h1> Merci </h1>
        <p> Merci pour vos commentaires. </p>
        </body>
        </html>
        <?php
        
        } else {
          echo $envoye;
        ?>
        <html>
        <head>
        <title> Une erreur s'est produite </title>
        </head>
        <body>
        <h1> Une erreur s'est produite </h1>
        <p> Nous n'avons pas pu envoyer vos commentaires. Veuillez réessayer. </p>
        </body>
        </html>
        <?php
        }
        ?>
  4. Exercice 03

    1. Énoncé
    2. Solution
      <!doctype html>
      <html lang="fr">
        <head>
          <!-- Required meta tags -->
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      
          <!-- Bootstrap CSS -->
          <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
      
          <title>Votre commande</title>
          <style>
      fieldset {
      			border: 2px solid #dcdcdc;
      			border-radius: 10px;
      			padding: 10px 20px;
      			text-align: leftt;
            width:50%;
      		}
          legend {
      		width:54%;
      		}    
      </style>
        </head>
        <body>
      <div class="container ">
      <form class="form-inline" action="<?= $_SERVER['PHP_SELF'] ?> " method="post" enctype="application/x-www-form-urlencoded" >
      <fieldset>
      <legend>Ajouter un commantaire</legend>
      <div class="row mb-2">
             <div class="col-lg-4" ">
                <label for="ex1" >Nom</label>
              </div>
              <div class="col-lg-8">
                <input  type="text" class="form-control" name="nom"  size="50" value="<?php if (
      isset($_POST['nom'])) echo htmlspecialchars($_POST['nom']);?>">
              </div>
        </div>
      <div class="row  mb-2">
              <div class="col-lg-4">
                <label for="ex1" >Prénom</label>
              </div>
              <div class="col-lg-8">
              <input  type="text"  class="form-control" name="prenom" size="50" value="<?php if
       (isset($_POST['prenom'])) echo htmlspecialchars($_POST['prenom']);?>">
              </div>
        </div>
      <div class="row mb-2 ">
              <div class="col-lg-4">
                <label for="ex1" >Email Adresse</label>
              </div>
              <div class="col-lg-8">
              <input  type="mail" class="form-control" name="email"  size="50" value="<?php if 
      (isset($_POST['email'])) echo htmlspecialchars($_POST['email']);?>">
              </div>
      </div>
      <div class="row mb-2">  
              <div class="col-lg-4">
                <label for="ex1" >Téléphone</label>
              </div>
              <div class="col-lg-8">
              <input  type="telephone" class="form-control" name="telephone"  size="50" value="
      <?php if (isset($_POST['telephone'])) echo htmlspecialchars($_POST['telephone']);?>">
              </div>
      </div>
      <div class="row mb-2">
              <div class="col-lg-4">
                <label for="ex1" >Commentaire</label>
              </div>
              <div class="col-lg-8">
              <textarea class="form-control" name="commentaire" cols="52" rows="4"><?php if (isset($_POST[
      'commentaire'])) echo htmlspecialchars($_POST['commentaire']);?></textarea>
              </div>
      </div>
      <div class="row mb-2">
      <div class="col-lg-6">
        <button type="reset" class="btn btn-primary mb-2 w-100" name="effacer">Effacer</button>
        </div>
        <div class="col-lg-6">
        <button type="submit" class="btn btn-primary mb-2 w-100" name="envoi">Envoyer</button>
         </div>
      </div>
      </fieldset>
      </form>
      
      <?php
      if(isset($_POST['email'])) {
       
          // EDIT THE 2 LINES BELOW AS REQUIRED
          $email_to = "hajjilina23@gmail.com";//votre@email
          $email_subject = "Essai";//Le sujet de votre email
       
          function died($error) {
              // your error code can go here
              echo 
      "Nous sommes désolés, mais des erreurs ont été détectées dans le" .
      " formulaire que vous avez envoyé. ";
              echo "Ces erreurs apparaissent ci-dessous.<br /><br />";
              echo $error."<br /><br />";
              echo "Merci de corriger ces erreurs.<br /><br />";
              die();
          }
       
       
          // si la validation des données attendues existe
           if(!isset($_POST['nom']) ||
              !isset($_POST['prenom']) ||
              !isset($_POST['email']) ||
              !isset($_POST['telephone']) ||
              !isset($_POST['commentaire'])) {
              died(
      'Nous sommes désolés, mais le formulaire que vous avez soumis semble poser' .
      ' problème.');
          }
       
           
       
          $nom = $_POST['nom']; // required
          $prenom = $_POST['prenom']; // required
          $email = $_POST['email']; // required
          $telephone = $_POST['telephone']; // not required
          $commentaire = $_POST['commentaire']; // required
       
          $error_message = "";
          $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
       
          if(!preg_match($email_exp,$email)) {
            $error_message .= 
      'L\'adresse e-mail que vous avez entrée ne semble pas être valide.<br />';
          }
         
            // Prend les caractères alphanumériques + le point et le tiret 6
            $string_exp = "/^[A-Za-z0-9 .'-]+$/";
         
          if(!preg_match($string_exp,$nom)) {
            $error_message .= 
      'Le nom que vous avez entré ne semble pas être valide.<br />';
          }
         
          if(!preg_match($string_exp,$prenom)) {
            $error_message .= 
      'Le prénom que vous avez entré ne semble pas être valide.<br />';
          }
         
          if(strlen($commentaire) < 2) {
            $error_message .= 
      'Le commentaire que vous avez entré ne semble pas être valide.<br />';
          }
         
          if(strlen($error_message) > 0) {
            died($error_message);
          }
       
          $email_message = "Détail.\n\n";
          $email_message .= "Nom: ".$nom."\n";
          $email_message .= "Prenom: ".$prenom."\n";
          $email_message .= "Email: ".$email."\n";
          $email_message .= "Telephone: ".$telephone."\n";
          $email_message .= "Commentaire: ".$commentaire."\n";
       
          // create email headers
          $headers = 'From: '.$email."\r\n".
          'Reply-To: '.$email."\r\n" .
          'X-Mailer: PHP/' . phpversion();
          mail($email_to, $email_subject, $email_message, $headers);
          ?>
           
          <!-- mettez ici votre propre message de succès en html -->
           
          Merci de nous avoir contacter. Nous vous contacterons très bientôt.
           
          <?php
      
          }
          ?>
          </div>
          <!-- Optional JavaScript -->
          <!-- jQuery first, then Popper.js, then Bootstrap JS -->
          <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
          <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
          <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
        </body>
      </html>