无法让 PHP 环境变量在本地工作 - Ubuntu 16.04

Can't get PHP environment variables to work locally - Ubuntu 16.04

在对所有文档、Whosebug 问题和博客文章进行彻底审查后,我可以解决这个特定问题...连同几个小时的故障排除,我仍然无法找到如何获取基本环境变量的用法在我的 Slim PHP 项目中工作。

这是我的第一个 PHP Web 应用程序项目,当然也是我第一次让环境变量在 PHP 中工作。

基本上我想做的是在本地 .htaccess 文件中将密码设置为环境变量,这样密码就不会在我推送到 GitHub 的代码中不安全地公开(.htaccess 在我的项目中被 git 设置为忽略。

我基本上想要以下代码:

.htaccess 文件:

SetEnv PASSWORD superSecretPassw0rd

稍后在我项目的 PHP 文件中的适当位置检索该变量并将其用于通过 SMTP 发送电子邮件。

例如 /app/routes.php:

$mail->Password = getenv("PASSWORD"); 

现在,我正在做第一部分,在 .htaccess 文件中设置环境变量。事实上,我已经尝试通过以下每种方式设置环境变量:

SetEnv HTTP_PASSWORD NeTzj6gKJp5q

SetEnv PASSWORD glop

RewriteRule .* - [E=TEST:PasswordJOKES10]

然而当我 var_dump(getenv("TEST")); 变量显示为 bool(false).

可能我的 .htaccess 文件根本没有被读取。当我删除 .htaccess 文件的内容时,所有内容基本上 运行 都是一样的,如果文件只是填充了长长的随机文本行,它也会这样做。

我也确保 module rewrite is enabled。所以这不是问题。

我还检查了 /etc/apache2/apache2.conf 的设置。最重要的设置看起来我已经设置好了:

<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

# AccessFileName: The name of the file to look for in each directory
# for additional configuration directives.  See also the AllowOverride
# directive.
AccessFileName .htaccess

AllowOverride All 被设置为 .htaccess 文件可以工作,AccessFileName 被设置为 .htaccess.

我项目的完整路径是/var/www/html/east-end-php-site/,目录结构基本是这样的:

/east-end-php-site/
  |-----> /app/
  |-----> /config/
  |-----> /vendor/
 composer.json
 README.md
 .htaccess
 index.php

我的本地设置:

项目是 运行 通过 运行ning 命令 php -S localhost:8000 在终端中从该目录的根目录。

我目前在这方面碰壁了。请Whosebug的战友告诉我,我做错了什么?接下来我应该在哪里进行故障排除?什么可以解决这个问题?

额外参考 1

整个 .htaccess 文件如下所示:

AllowOverride ALL

RewriteEngine On

SetEnv HTTP_TEST NeTzj6gKJp5q

SetEnv TEST glop


# Some hosts may require you to use the `RewriteBase` directive.
# If you need to use the `RewriteBase` directive, it should be the
# absolute physical path to the directory that contains this htaccess file.

RewriteBase /var/www/html/east-end-php-site/

RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]


RewriteCond %{REQUEST_URI}:: ^(/.+)(.+)::$
RewriteRule ^(.*) - [E=BASE:%1]
RewriteRule ^(.*)$ %{ENV:BASE}index.php [NC,L]

RewriteRule .* - [E=TEST:PasswordJOKES10]
  1. .htaccess 仅适用于 apache,不适用于内置网络服务器
  2. 要模拟 $_ENV 变量,您应该使用 https://github.com/vlucas/phpdotenv