PHP Email Verification - Tutorial by Mailtrap

Поділитися
Вставка
  • Опубліковано 31 гру 2024

КОМЕНТАРІ • 9

  • @jigpogixx1026
    @jigpogixx1026 3 місяці тому

    Beginner here! Can I also integrate or use that functionality to codeigniter 4 framework? need some guidance

    • @mailtrap.
      @mailtrap.  3 місяці тому

      Thanks for watching! And thank you for your question.
      Let's see.
      The core concept of email verification in PHP is the same as in CodeIgniter 4 since CodeIgniter 4 is built using PHP. Both approaches follow similar steps:
      User Registration: Store user details and a verification token in the database.
      Email Sending: Send an email with a unique link containing the token.
      Token Verification: When the user clicks the link, check the token and activate the user account.
      However, CodeIgniter 4 provides a framework structure and built-in libraries to simplify this process compared to raw PHP. Let me break down the differences:
      Key Differences:
      Framework Support:
      PHP: You need to manually handle everything-database connection, query preparation, email configuration, validation, routing, etc.
      CodeIgniter 4: It offers pre-built classes for emailing, routing, and database handling, which reduces code complexity. CodeIgniter's built-in services like Email make it easier to send emails.
      Routing:
      PHP: You’ll need to define the routing manually or use .htaccess to handle dynamic URLs for token verification.
      CodeIgniter 4: Routes are configured via the app/Config/Routes.php file, simplifying the process of mapping URLs to controller actions.
      Security:
      PHP: You need to manually implement security measures, such as sanitizing input, hashing passwords, and escaping data.
      CodeIgniter 4: The framework has built-in security features like CSRF protection, XSS filtering, and input validation, reducing the risk of common vulnerabilities.
      Email Handling:
      PHP: You would typically use mail() or external libraries like PHPMailer to send emails.
      CodeIgniter 4: The framework offers its own Email library, which simplifies email sending, configuration, and error handling.
      Validation:
      PHP: You must manually validate email addresses, user input, and token handling.
      CodeIgniter 4: Offers a validation library that helps validate user input with predefined rules.
      Check out this code comparisons:
      Raw PHP Verification:
      // registration.php (User Registration)
      $email = $_POST['email'];
      $token = bin2hex(random_bytes(16));
      $hashedPassword = password_hash($_POST['password'], PASSWORD_DEFAULT);
      // Save user and token to the database
      $pdo->prepare("INSERT INTO users (email, password, token) VALUES (?, ?, ?)")
      ->execute([$email, $hashedPassword, $token]);
      // Send email
      $subject = "Verify your email";
      $message = "Please click the link to verify your email: yourdomain.com/verify.php?token=$token";
      mail($email, $subject, $message);
      // verify.php (Verification)
      $token = $_GET['token'];
      $stmt = $pdo->prepare("SELECT * FROM users WHERE token = ?");
      $stmt->execute([$token]);
      $user = $stmt->fetch();
      if ($user) {
      // Verify user
      $pdo->prepare("UPDATE users SET token = NULL, is_verified = 1 WHERE id = ?")
      ->execute([$user['id']]);
      echo "Email verified!";
      } else {
      echo "Invalid token!";
      }
      CodeIgniter 4 example:
      // app/Controllers/AuthController.php
      use App\Models\UserModel;
      class AuthController extends BaseController
      {
      public function register()
      {
      $userModel = new UserModel();
      $userData = [
      'email' => $this->request->getPost('email'),
      'password' => password_hash($this->request->getPost('password'), PASSWORD_DEFAULT),
      'email_verification_token' => bin2hex(random_bytes(16)),
      ];
      if ($userModel->insert($userData)) {
      $this->sendVerificationEmail($userData['email'], $userData['email_verification_token']);
      return redirect()->to('/login')->with('message', 'Please check your email to verify your account.');
      }
      return redirect()->back()->withInput()->with('error', 'Registration failed');
      }
      private function sendVerificationEmail($email, $token)
      {
      $emailService = \Config\Services::email();
      $emailService->setTo($email);
      $emailService->setFrom('no-reply@yourdomain.com', 'Your Website');
      $emailService->setSubject('Verify your email');
      $emailService->setMessage("Click the link to verify your email: " . base_url('auth/verify/' . $token));
      $emailService->send();
      }
      public function verify($token)
      {
      $userModel = new UserModel();
      $user = $userModel->where('email_verification_token', $token)->first();
      if ($user) {
      $userModel->update($user['id'], ['email_verification_token' => null, 'is_verified' => 1]);
      return redirect()->to('/login')->with('message', 'Email successfully verified!');
      }
      return redirect()->to('/login')->with('error', 'Invalid token!');
      }
      }
      We hope this helps.
      Let us know. Good luck!

  • @ElmoPlayss
    @ElmoPlayss 3 місяці тому

    This is not working, SMTP Error: Could not authenticate.

    • @ivandjuric3676
      @ivandjuric3676 3 місяці тому

      Hey man, I got the same error when I set up MT a while ago. The thing that bugged me was that I thought it was like Gmail SMTP, so I used my Mailtrap account name instead of 'username' that's in the credentials tab. Hope it helps my guy 🍻

    • @mailtrap.
      @mailtrap.  3 місяці тому +1

      Hey, thanks for your help and comment! Yes, it's true. One needs to use username from MT credentials, not the account name!
      Cheers! Thanks for being with us! Stay tuned!

    • @whitishcreates
      @whitishcreates Місяць тому

      Bro please help me. I am working on a to do list web app in which I want to send email notificationfor those users whose tasks are pending. And I am stuck 😢😢😢

    • @ivandjuric3676
      @ivandjuric3676 Місяць тому

      @@whitishcreates which language/framework my guy?

    • @whitishcreates
      @whitishcreates Місяць тому

      @@ivandjuric3676 php and mysql.