Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-mini-2024-07-18· OpenAIAi2 WildChat-4.8M (AI2)

<?php requireonce DIR_ . '/../models/UserModel.php'; class…

  1. User

    Assistant:

    User: <?php require_once DIR . '/../models/UserModel.php';

    class UserController { private $userModel;

    public function __construct() {
        $this->userModel = new UserModel();
    }
    
    // Gestion de la connexion
    public function login() {
    
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $email = trim($_POST['email']);
            $password = $_POST['password'];
            $remember = isset($_POST['remember']);
    
    
            // Vérification des champs vides
            if (empty($email) || empty($password)) {
                $_SESSION['message'] = [
                    'type' => 'error',
                    'text' => 'Tous les champs sont obligatoires.'
                ];
                include_once "../views/loginView.php";
                exit;
            }
    
            // Recherche de l'utilisateur par email
            $user = $this->userModel->findByEmail($email);
    
            if (!$user) {
                $_SESSION['message'] = [
                    'type' => 'error',
                    'text' => 'Adresse email introuvable.'
                ];
            } elseif (!$this->userModel->verifyPassword($password, $user['password'])) {
                $_SESSION['message'] = [
                    'type' => 'error',
                    'text' => 'Mot de passe incorrect.'
                ];
            } else {
                // Connexion réussie
                $_SESSION['user'] = $user;
                // Gérer le cookie "remember_me"
                if ($remember) {
                // Créer un cookie valable 30 jours
                    setcookie('remember_me', $email, time() + (30 * 24 * 60 * 60), "/");
                } else {
                // Supprimer le cookie s'il existe
                    setcookie('remember_me', '', time() - 3600, "/");
        }
    
                
                $_SESSION['message'] = [
                    'type' => 'success',
                    'text' => 'Connexion réussie. Bienvenue, ' . htmlspecialchars($user['fullname']) . ' !'
                ];
                exit;
            }
    
            // Redirection vers la page de connexion avec un message d'erreur
            include_once "../views/loginView.php";
            exit;
        }
    }
    
    // Gestion de l'inscription
    public function register() {
    
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $fullname = trim($_POST['fullname']);
            $email = trim($_POST['email']);
            $password = $_POST['password'];
            $confirmPassword = $_POST['confirm_password'];
    
            // Liste des erreurs
            $errors = [];
    
            // Validation des champs
            if (empty($fullname)) {
                $errors[] = 'Le champ "Nom complet" est obligatoire.';
            }
    
            if (empty($email)) {
                $errors[] = 'Le champ "Email" est obligatoire.';
            } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $errors[] = 'L\'adresse email n\'est pas valide.';
            }
    
            if (empty($password)) {
                $errors[] = 'Le champ "Mot de passe" est obligatoire.';
            }
    
            if (empty($confirmPassword)) {
                $errors[] = 'Le champ "Confirmer le mot de passe" est obligatoire.';
            }
    
            if (!empty($password) && !empty($confirmPassword) && $password !== $confirmPassword) {
                $errors[] = 'Les mots de passe ne correspondent pas.';
            }
    
            // Vérification si l'email existe déjà
            if (empty($errors) && $this->userModel->emailExists($email)) {
                $errors[] = 'Cet email est déjà utilisé.';
            }
    
            // Affichage des erreurs si elles existent
            if (!empty($errors)) {
                $_SESSION['message'] = [
                    'type' => 'error',
                    'text' => implode('<br>', $errors)
                ];
                include_once "../views/registerView.php";
                exit;
            }
    
            // Si tout est bon, hashage du mot de passe
            $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
    
            // Inscription de l'utilisateur
            if ($this->userModel->registerUser($fullname, $email, $hashedPassword)) {
                $_SESSION['message'] = [
                    'type' => 'success',
                    'text' => 'Inscription réussie ! Vous pouvez maintenant vous connecter.'
                ];
                include_once "../views/registerView.php";
                exit;
            } else {
                $_SESSION['message'] = [
                    'type' => 'error',
                    'text' => 'Une erreur est survenue. Veuillez réessayer.'
                ];
                exit;
            }
        }else{
            include_once "../views/registerView.php";
        }
    }
    public function forgotPassword() {
    
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $email = trim($_POST['email']);
    
            // Vérifier si l'email est vide
            if (empty($email)) {
                $_SESSION['message'] = [
                    'type' => 'error',
                    'text' => 'Veuillez entrer une adresse email.'
                ];
                include_once "../views/forgotPasswordView.php";
    
                exit;
            }
    
            // Vérifier si l'email existe
            $user = $this->userModel->findByEmail($email);
            if (!$user) {
                $_SESSION['message'] = [
                    'type' => 'error',
                    'text' => 'Aucun compte n\'est associé à cet email.'
                ];
                include_once "../views/forgotPasswordView.php";
                exit;
            }
    
            // Générer un token unique pour la réinitialisation
            $resetToken = bin2hex(random_bytes(32));
            $expiry = date('Y-m-d H:i:s', strtotime('+1 hour'));
    
            // Stocker le token et l'expiration dans la base de données
            $this->userModel->storeResetToken($user['id'], $resetToken, $expiry);
    
            // Générer le lien de réinitialisation
            $resetLink = BASE_URL . 'views/resetPasswordView.php?token=' . $resetToken;
    
            // Afficher le lien de réinitialisation sur la page
            $_SESSION['reset_link'] = $resetLink;
    
            $_SESSION['message'] = [
                'type' => 'success',
                'text' => 'Lien de réinitialisation généré. Cliquez sur le lien ci-dessous pour réinitialiser votre mot de passe.'
            ];
    
            include_once "../views/forgotPasswordView.php";
            exit;
        }else{
            include_once "../views/forgotPasswordView.php";
        }
    }
    
    
    public function resetPassword() {
    
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $token = trim($_POST['token']);
            $password = $_POST['password'];
            $confirmPassword = $_POST['confirm_password'];
    
            // Vérifier si les champs sont vides
            if (empty($token) || empty($password) || empty($confirmPassword)) {
                $_SESSION['message'] = [
                    'type' => 'error',
                    'text' => 'Tous les champs sont obligatoires.'
                ];
    
                $_GET["token"] = $token; 
                include_once "../views/resetPasswordView.php";
    
                exit;
            }
    
            // Vérifier si les mots de passe correspondent
            if ($password !== $confirmPassword) {
                $_SESSION['message'] = [
                    'type' => 'error',
                    'text' => 'Les mots de passe ne correspondent pas.'
                ];
                $_GET["token"] = $token; 
                include_once "../views/resetPasswordView.php";
                
                exit;
            }
    
            // Rechercher l'utilisateur via le token
            $user = $this->userModel->findByResetToken($token);
            if (!$user) {
                $_SESSION['message'] = [
                    'type' => 'error',
                    'text' => 'Token de réinitialisation invalide ou expiré.'
                ];
                include_once "../views/loginView.php";
                exit;
            }
    
            // Hacher le nouveau mot de passe
            $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
    
            // Mettre à jour le mot de passe dans la base de données et réinitialiser le token
            if ($this->userModel->updatePassword($user['id'], $hashedPassword)) {
                $_SESSION['message'] = [
                    'type' => 'success',
                    'text' => 'Votre mot de passe a été réinitialisé avec succès. Vous pouvez maintenant vous connecter.'
                ];
                include_once "../views/loginView.php";
                exit;
            } else {
                $_SESSION['message'] = [
                    'type' => 'error',
                    'text' => 'Une erreur est survenue. Veuillez réessayer.'
                ];
                $_GET["token"] = $token; 
                include_once "../views/resetPasswordView.php";
                
                exit;
            }
        }else{
            include_once "../views/resetPasswordView.php";
    
        }
    }
    
    
    
    

    } ?>

    Warning: include_once(../views/forgotPasswordView.php): Failed to open stream: No such file or directory in /home/etudiants/info/emephara/local_html/modules/mod_connexion/controllers/UserController.php on line 189

    Warning: include_once(): Failed opening '../views/forgotPasswordView.php' for inclusion (include_path='.:/usr/share/php') in /home/etudiants/info/emephara/local_html/modules/mod_connexion/controllers/UserController.php on line 189 Assistant:

  2. Assistant

    The warnings you are encountering indicate that the PHP script is trying to include a file (forgotPasswordView.php in this case) but cannot find it. This typically happens due to a misconfigured file path.

    Here are some steps to troubleshoot and fix the issue:

    1. Check File Path: Ensure that the forgotPasswordView.php file actually exists in the specified path relative to the current script. The include_once statement in your code is attempting to include the file using ../views/forgotPasswordView.php. This means it is looking for a folder named views one directory up from the current script's location. Confirm that the file exists in that path.

    2. Verify Directory Structure:

      • The file structure should look something like this:
        /modules
           /mod_connexion
               /controllers
                   UserController.php
               /models
                   UserModel.php
               /views
                   forgotPasswordView.php
                   resetPasswordView.php
                   registerView.php
                   loginView.php
        
      • If your structure is different, adjust the path accordingly. For example, if views is actually within mod_connexion, the include path should be adjusted to views/forgotPasswordView.php.
    3. Use Absolute Paths: To avoid path issues, consider using absolute paths instead of relative paths. This can be achieved by defining a constant at the beginning of your script (or in a common config file) that specifies the base directory of your project. For example:

      define('BASE_DIR', __DIR__ . '/../views/');
      

      Then you can include files like this:

      include_once BASE_DIR . 'forgotPasswordView.php';
      
    4. Error Reporting: Ensure error reporting is turned on to see any additional warnings or errors that might help with debugging:

      error_reporting(E_ALL);
      ini_set('display_errors', 1);
      
    5. File Permissions: Double-check the file permissions for the included files to ensure that they are readable by the server.

    6. Review Autoloaders: If you're using a framework or a custom autoloader, ensure that the models, controllers, and views folders are properly registered in the autoload configuration if needed.

    Following these steps should help you identify and fix the issues related to file inclusion in your PHP application. If you continue to face problems, please share the directory structure and any relevant configurations.