如何在 php 中从 .env 文件加载数据
Posted
技术标签:
【中文标题】如何在 php 中从 .env 文件加载数据【英文标题】:How to load data from .env file in php 【发布时间】:2022-01-18 07:57:21 【问题描述】:我的网站上有一个联系表格,它会将其内容邮寄到一个电子邮件 ID。 我已经使用 phpMailer 完成任务,但密码是直接存储的 在一个变量中。我想从 .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");
这是我的 .env 文件的样子:
PASSWORD="PASSWORD"
如何从 env 文件中获取密码?
【问题讨论】:
【参考方案1】:你可以试试这个。
$_ENV["PASSWORD"]
【讨论】:
【参考方案2】:您可以使用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'] ?? '';
【讨论】:
以上是关于如何在 php 中从 .env 文件加载数据的主要内容,如果未能解决你的问题,请参考以下文章
如何在 laravel 5.2 中从 url 中删除 public