How to get system environment variables into PHP while running CLI & Apache2Handler?
I had exactly the same problem. To solve it, I just sourced /etc/environment
inside /etc/apache2/envvars
.
The content of /etc/environment
:
export MY_PROJECT_PATH=/var/www/my-project
export MY_PROJECT_ENV=production
export MY_PROJECT_MAIL=support@my-project.com
The content of /etc/apache2/envvars
:
# Load all the system environment variables.
. /etc/environment
Now, I'm able to use these variables in the Apache Virtual Host config files and in PHP.
Here's an example of an Apache virtual host:
<VirtualHost *:80>
ServerName my-project.com
ServerAlias www.my-project.com
ServerAdmin ${MY_PROJECT_MAIL}
UseCanonicalName On
DocumentRoot ${MY_PROJECT_PATH}/www
# Error log.
ErrorLog ${APACHE_LOG_DIR}/my-project.com_error.log
LogLevel warn
# Access log.
<IfModule log_config_module>
LogFormat "%h %l %u %t \"%m %>U%q\" %>s %b %D" clean_url_log_format
CustomLog ${APACHE_LOG_DIR}/my-project.com_access.log clean_url_log_format
</IfModule>
# DocumentRoot directory
<Directory ${MY_PROJECT_PATH}/www>
# Disable .htaccess rules completely, for better performance.
AllowOverride None
Options FollowSymLinks Includes
Order deny,allow
Allow from All
Include ${MY_PROJECT_PATH}/config/apache/inc.mime-types.conf
Include ${MY_PROJECT_PATH}/config/apache/inc.cache-control.conf
# Rewrite rules.
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
# Include all the common rewrite rules (for http and https).
Include ${MY_PROJECT_PATH}/config/apache/inc.rewriterules-shared.conf
</IfModule>
</Directory>
</VirtualHost>
And this is an example of how to access them with PHP:
<?php
header('Content-Type: text/plain; charset=utf-8');
print getenv('MY_PROJECT_PATH') . "\n" .
getenv('MY_PROJECT_ENV') . "\n" .
getenv('MY_PROJECT_MAIL') . "\n";
?>
How to Dynamically Set Enviroment Variables in Apache2
This was never really resolved.
In the end we analysed the codebase and found that the custom enviroment variable was not needed and blanket replaced it with DOCUMENT_ROOT
One caveat was needing to ensure DOCUMENT_ROOT was set / passed in for cronjobs or cli operations.
Related Topics
How to Generate Random Date Between Two Dates Using PHP
Deep Recursive Array of Directory Structure in PHP
How to Include the Split Delimiter in Results for Preg_Split()
Date Function Output in a Local Language
Is It Wise to Use PHP for a Daemon
Generating Xml Document in PHP (Escape Characters)
How to Store Null Values in Datetime Fields in MySQL
Best Way to Transfer an Array Between PHP and JavaScript
Setting Value of a HTML Form Textarea
Formatting Phone Numbers in PHP
Correct Way to Set Bearer Token with Curl
Expected Response Code 220 But Got Code "", with Message "" in Laravel
Add a Prefix to Each Item of a PHP Array