Home > Net >  How to load data from .env file in php
How to load data from .env file in php

Time:12-15

I have a contact form in my website which mails its contents to an email id.
I have used PHPMailer to accomplish the task but the password is directly stored
in a variable. I want to load the Password from a .env file. How do I do that? Here's the code:

<?php
  use PHPMailer\PHPMailer\PHPMailer;
  use PHPMailer\PHPMailer\SMTP;
  use PHPMailer\PHPMailer\Exception;

    require '../vendor/autoload.php';

    $mail = new PHPMailer(true);

    $firstName = $_POST['firstName'];
    $lastName = $_POST['lastName'];
    $email = $_POST['email'];
    $message = $_POST['message'];

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      header("location: ../index.php?error=invalidemail");
    } else if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
      try {
        //Server settings
        $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      //Enable verbose debug output
        $mail->isSMTP();                                            //Send using SMTP
        $mail->Host       = 'smtp.gmail.com';                     //Set the SMTP server to send through
        $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
        $mail->Username   = '[email protected]';                     //SMTP username
        $mail->Password   = 'PASSWORD';                               //SMTP password
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
        $mail->Port       = 465;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
    
        //Recipients
        // $mail->setFrom('[email protected]', 'Name');
        $mail->addAddress('[email protected]');     //Add a recipient
        // $mail->addAddress('[email protected]');               //Name is optional
        // $mail->addReplyTo('[email protected]', 'Information');
        // $mail->addCC('[email protected]');
        // $mail->addBCC('[email protected]');
    
        //Attachments
        // $mail->addAttachment('/var/tmp/file.tar.gz');         //Add attachments
        // $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    //Optional name
    // .'<br>'
        //Content
        $mail->isHTML(true);                                  //Set email format to HTML
        $mail->Subject = 'New Form Submission in Website';
        $mail->Body    = '<h1>There is a new form submission in the website, here are the details:</h1> <br>' . 'Name: '.$firstName .' '.$lastName .'<br>' .'Email: ' .$email.'<br>' . 'Message:'.'<br>'. $message;
        // $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
    
        $mail->send();
        echo 'Message has been sent';
        header("location: ../index.php?error=none");
    } catch (Exception $e) {
      header("location: ../index.php?error=stmtfailed");
    }
   }

and here is what my .env file looks like:

PASSWORD="PASSWORD"

How do I get the Password from the env file?

CodePudding user response:

You can try this.

$_ENV["PASSWORD"]

CodePudding user response:

You can use symfony/dotenv. First install it with composer, then this:

use Symfony\Component\Dotenv\Dotenv;

$dotenv = new Dotenv();
$dotenv->load(__DIR__.'/../.env'); // please update this path for your case

// You will get the variable both in
// $_ENV['PASSWORD'] and $_SERVER['PASSWORD'].
$password = $_ENV['PASSWORD'] ?? '';
  • Related