8768 sujets

Développement web côté serveur, CMS

bonsoir la communauté,
quelqu'un pourrait-il m'eclairer ? j'essaye de construire un système de mot de passe oublié
j'ai deux erreurs

Notice: Undefined variable: db in C:\wamp\www\ndameyong\forgot.php on line 18

Fatal error: Uncaught Error: Call to a member function prepare() on null in C:\wamp\www\ndameyong\forgot.php:18 Stack trace: #0 {main} thrown in C:\wamp\www\ndameyong\forgot.php on line 18
voilà les codes
forgot.php
<?php require 'includes/includes.php' ?>

<?php 
$titrepage="Mot de passe oublié || Ndameyong - L'Ecole des Langues Camerounaises" ;

if(!empty($_POST))
{
    $post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
    extract($post);

    $errors = [];


    if(empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)){
      array_push($errors, 'Cette email est invalide.');
    }
    else{
     $req = $db->prepare('SELECT * FROM users WHERE email=:email');
     $req->bindValue(':email', $email, PDO::PARAM_STR);
     $req->execute();

      if(!$req->rowCount()){
        array_push($errors, 'Cet email ne correspond à aucun membre du site.');
      }
      else{
        $user = $req->fetch();
      }

      if(empty($errors))
      {
        $token = uniqid();

        $req = $db->prepare('INSERT INTO password_resets (email, token, created_at) VALUES (:email, :token, NOW())');
        $req->bindValue(':email', $email, PDO::PARAM_STR);
        $req->bindValue(':token', $token, PDO::PARAM_STR);
        $req->execute();

        $link = 'Bonjour, veuillez cliquer sur <a href="https://ndameyong.test/reset.php?token='.$token.'">ce lien</a> pour réinitialiser votre mote de passe.';

        // Create the Transport
        $transport = (new Swift_SmtpTransport('smtp.mailtrap.io', 465))
          ->setUsername('fae489573327ac')
          ->setPassword('eed3d4ab64b373')
        ;

        // Create the Mailer using your created Transport
        $mailer = new Swift_Mailer($transport);

        // Create a message
        $message = (new Swift_Message('Mot de passe oublié'))
          ->setFrom(['lcorrefabien@gmail.com' => 'John Doe'])
          ->setTo([$email => $user->name])
          ->addPart($link, 'text/html');
          ;

        // Send the message
        $result = $mailer->send($message);

        if($result){
          $success = 'Un email vous a été envoyé avec des instructions.';
          unset($email);
        }
      }
    }
}

?>

<?php require 'includes/header.php'; ?>


<!-- message de session -->
<?php if (isset($_SESSION['message'])): ?>
  <div class="message"> <?php echo $_SESSION['message']; ?></div>
  <?php unset($_SESSION['message']) ?>
<?php endif ?>
<?php if (isset($_SESSION['erreur'])): ?>
  <div class="errorMessage"> <?php echo $_SESSION['erreur']; ?></div>
  <?php unset($_SESSION['erreur']) ?>
<?php endif ?>


	<h4 class="title-element">Récupération de mot de passe</h4>
	
 <?php include('messages.php');?>

    <form action="forgot.php" method="post">
      <div class="form-group">
        <label for="email">Email</label>
        <input type="email" name="email" class="form-control" placeholder="Email" value="<?= $email ?? '';?>">
      </div>
      <button type="submit" class="btn btn-primary">Envoyer</button>
    </form>
    <br>

    <p><a href="login.php">Je m'en souviens en fait.</a></p>
    

	
<?php require 'includes/footer2.php'; ?>


Db.php
<?php
 
/**
* Gestion de la base de données
*/
class Db{
     
    private $host=HOST;
    private $name=DBNAME;
    private $user=USER;
    private $pass=PWD;
 
    private $connexion;
 
    function __construct($host=null,$name=null,$user=null,$pass=null){
         
        if($host != null){
            $this->host = $host;
            $this->name = $name;
            $this->user = $user;
            $this->pass = $pass;
        }
 
        try{
 
            $this->connexion = new PDO('mysql:host='.$this->host.';dbname='.$this->name,
                $this->user,$this->pass,array(
                    1002 =>'SET NAMES UTF8',
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING


              
                    ));
            $this->connexion->exec('SET NAMES utf8');
//PDO::MYSQL_ATTR_INIT_COMMAND
        }catch (PDOException $e){
            //echo 'Erreur : Impossible de se connecter  à la BD !';die();
            echo $e->getMessage();
        }
    }
 
    /* requete */
 
    public function query($sql , $data=array()){
        $req = $this->connexion->prepare($sql);
        $req->execute($data);
        return $req->fetchAll(PDO::FETCH_OBJ);
    }
 
    public function tquery($sql , $data=array()){
        $req = $this->connexion->prepare($sql);
        $req->execute($data);
        return $req->fetchAll(PDO::FETCH_ASSOC);
    }
 
 
    public function insert($sql , $data=array()){
        $req = $this->connexion->prepare($sql);
        $nb=$req->execute($data);
        return $nb;
    }
    
	
	public function exec($sql , $data=array()){
      try{
        $req = $this->connexion->prepare($sql);
        $req->execute($data);
        return $req->rowCount(); // Retourne le nombre de lignes impactées par la reuqête
      }catch(Exception $e){
        echo 'Erreur : ' . $e->getMessage(); // en cas d'erreur dans la requête !
      }
    }


    {
       $sql = 'DELETE FROM users WHERE id=:id';
       $data = [':id'=>$id]; 
       return  $DB->exec($sql , $data) ;
    }
	
}
Bonjour,

Oui, sur la ligne en question, tu fais :
$req = $db->prepare('SELECT * FROM users WHERE email=:email');

mais l'objet $db n'est pas instancié avant.

Je vois que tu as aussi fait une classe Db que tu n'utilise pas ?
Bjr merci de m'avoir répondu
suite à votre réponse comment faire pour instancier $db???
forgot.php modifié

<?php require 'includes/includes.php' ?>

<?php 
$titrepage="Mot de passe oublié || Ndameyong - L'Ecole des Langues Camerounaises" ;

if(!empty($_POST))
{
    $post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
    extract($post);

    $errors = [];


    if(empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)){
      array_push($errors, 'Cette email est invalide.');
    }
    else{
       $req = $db->prepare('SELECT * FROM users WHERE email=:email');
      
      if(!$req->rowCount()){
        array_push($errors, 'Cet email ne correspond à aucun membre du site.');
      }
      else{
        $user = $req->fetch();
      }

      if(empty($errors))
      {
        $token = uniqid();

        $req = $db->prepare('INSERT INTO password_resets (email, token, created_at) VALUES (:email, :token, NOW())');
        $req->bindValue(':email', $email, PDO::PARAM_STR);
        $req->bindValue(':token', $token, PDO::PARAM_STR);
        $req->execute();

        $link = 'Bonjour, veuillez cliquer sur <a href="https://ndameyong.test/reset.php?token='.$token.'">ce lien</a> pour réinitialiser votre mote de passe.';

        // Create the Transport
        $transport = (new Swift_SmtpTransport('smtp.mailtrap.io', 465))
          ->setUsername('fae489573327ac')
          ->setPassword('eed3d4ab64b373')
        ;

        // Create the Mailer using your created Transport
        $mailer = new Swift_Mailer($transport);

        // Create a message
        $message = (new Swift_Message('Mot de passe oublié'))
          ->setFrom(['lcorrefabien@gmail.com' => 'John Doe'])
          ->setTo([$email => $user->name])
          ->addPart($link, 'text/html');
          ;

        // Send the message
        $result = $mailer->send($message);

        if($result){
          $success = 'Un email vous a été envoyé avec des instructions.';
          unset($email);
        }
      }
    }
}

?>

<?php require 'includes/header.php'; ?>


<!-- message de session -->
<?php if (isset($_SESSION['message'])): ?>
  <div class="message"> <?php echo $_SESSION['message']; ?></div>
  <?php unset($_SESSION['message']) ?>
<?php endif ?>
<?php if (isset($_SESSION['erreur'])): ?>
  <div class="errorMessage"> <?php echo $_SESSION['erreur']; ?></div>
  <?php unset($_SESSION['erreur']) ?>
<?php endif ?>


	<h4 class="title-element">Récupération de mot de passe</h4>
	
 <?php include('messages.php');?>

    <form action="forgot.php" method="post">
      <div class="form-group">
        <label for="email">Email</label>
        <input type="email" name="email" class="form-control" placeholder="Email" value="<?= $email ?? '';?>">
      </div>
      <button type="submit" class="btn btn-primary">Envoyer</button>
    </form>
    <br>

    <p><a href="login.php">Je m'en souviens en fait.</a></p>
 
<?php require 'includes/footer2.php'; ?>


Db.php

<?php
 
/**
* Gestion de la base de données
*/
class Db{
     
    private $host=HOST;
    private $name=DBNAME;
    private $user=USER;
    private $pass=PWD;
 
    private $connexion;
 
    function __construct($host=null,$name=null,$user=null,$pass=null){
         
        if($host != null){
            $this->host = $host;
            $this->name = $name;
            $this->user = $user;
            $this->pass = $pass;
        }
 
        try{
 
            $this->connexion = new PDO('mysql:host='.$this->host.';dbname='.$this->name,
                $this->user,$this->pass,array(
                    1002 =>'SET NAMES UTF8',
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING


              
                    ));
            $this->connexion->exec('SET NAMES utf8');
//PDO::MYSQL_ATTR_INIT_COMMAND
        }catch (PDOException $e){
            //echo 'Erreur : Impossible de se connecter  à la BD !';die();
            echo $e->getMessage();
        }
    }
 
    /* requete */
 
    public function query($sql , $data=array()){
        $req = $this->connexion->prepare($sql);
        $req->execute($data);
        return $req->fetchAll(PDO::FETCH_OBJ);
    }
 
    public function tquery($sql , $data=array()){
        $req = $this->connexion->prepare($sql);
        $req->execute($data);
        return $req->fetchAll(PDO::FETCH_ASSOC);
    }
 
 
    public function insert($sql , $data=array()){
        $req = $this->connexion->prepare($sql);
        $nb=$req->execute($data);
        return $nb;
    }
    
	
	public function exec($sql , $data=array()){
      try{
        $req = $this->connexion->prepare($sql);
        $req->execute($data);
        return $req->rowCount(); // Retourne le nombre de lignes impactées par la reuqête
      }catch(Exception $e){
        echo 'Erreur : ' . $e->getMessage(); // en cas d'erreur dans la requête !
      }
    }

    public function deleteuser($id){
       $sql = 'DELETE FROM users WHERE id=:id';
       $data = [':id'=>$id]; 
       return  $DB->exec($sql , $data) ;
    }
 
    public function select($sql, $data=array()){
       $req = $this->connexion->prepare($sql);
       $data = prepared_query($DB, $sql, [$email]);
       $user = $data->get_result()->fetch_assoc();
    }
}


auth.php

<?php 

/**
* Auth
*/
class Auth{
	
	public static function islog($db){
		if(isset($_SESSION['user']) && isset($_SESSION['user']['email'])  && isset($_SESSION['user']['password'])){

			$data =array(
				'email'=>$_SESSION['user']['email'],
				'password'=>$_SESSION['user']['password']
				
				);
			
			$sql = 'SELECT * FROM users WHERE email=:email AND password=:password limit 1';
			$req = $db->tquery($sql,$data);

			if(!empty($req)){
				return true;
			}
		}
		return false;
	}


	public static function hashPassword($pass){

		return sha1(SALT.md5($pass.SALT).sha1(SALT));
	}


	public static function isadmin($db){
		if(isset($_SESSION['user']['role']) && (Auth::hashPassword('admin')  == $_SESSION['user']['role'])){
			return true;
		}
		return false;
	}

  public function uniqueEmail($email){
        $req = $this->connexion->prepare('SELECT count(*) as nbre from users WHERE email=:email limit 1');
        $req->execute(array('email'=>$email));
 
        $reponse = $req->fetchAll(PDO::FETCH_ASSOC);
        return $reponse[0]['nbre'];
 
    }
	public function deleteuser($id){
	   $sql = 'DELETE FROM users WHERE id=:id';
	   $data = [':id'=>$id]; 
	   return  $DB->exec($sql , $data) ;
	}
	
}