[英]How to load data from .env file in php
我的网站上有一个联系表格,将其内容邮寄到 email id。
我已经使用 PHPMailer 完成任务,但密码是直接存储的
在一个变量中。 我想从 a.env 文件加载密码。 我怎么做? 这是代码:
<?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@gmail.com'; //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@gmail.com', 'Name');
$mail->addAddress('email@gmail.com'); //Add a recipient
// $mail->addAddress('email@gmail.com'); //Name is optional
// $mail->addReplyTo('email@gmail.com', 'Information');
// $mail->addCC('cc@example.com');
// $mail->addBCC('bcc@example.com');
//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");
}
}
这是 my.env 文件的样子:
PASSWORD="PASSWORD"
如何从 env 文件中获取密码?
你可以试试这个。
$_ENV["PASSWORD"]
您可以使用symfony/dotenv 。 首先用composer安装它,然后是:
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'] ?? '';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.