1

I have a solution develop with PHP

  1. Framework Phalcon 3.4.5
  2. macOS 12.6
  3. PHP 7.3.33
  4. MAMP Pro 6

I have this .htaccess that is in my root folder:

A SetEnv directive is set like that:

<IfModule mod_env.c>
SetEnv APPLICATION_ENV=development
</IfModule>

The right env module are loaded in Apache:

  1. mod_env.so
  2. mod_setenvif.so

My host config have AllowAoverride All My AccessFileName is set to htaccess

I use this code in my index file to read the environment variable and I can't get the value.

defined('ENVIRONMENT') || define('ENVIRONMENT', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));

echo ENVIRONMENT . PHP_EOL;

Considering the SetEnv in the htaccess, should get development has a value, but I keep getting production.

I did test to be sure that mod_env and mod_setenvif are loaded. There is no error in my apache log and php log.

I have no clue why. Any help will be welcome here?

Thank you!

Daniel
  • 35
  • 4
  • Do you see the env var in `$_SERVER` by any chance?. You could also try [apache_getenv](https://www.php.net/manual/en/function.apache-getenv.php) – zanderwar Jan 15 '23 at 15:37
  • Do you have any other directives in your .htaccess file? – MrWhite Jan 15 '23 at 15:45
  • ... the "gotcha" with setting env vars in `.htaccess` is if you have mod_rewrite directives that cause the rewrite engine to "loop" (eg. many front-controller patterns). If this happens then the env var is renamed with a `REDIRECT_` prefix and it's this _renamed_ env var that gets imported by PHP. – MrWhite Jan 15 '23 at 17:00
  • 1
    @MrWhite You're right. I observed the presence of REDIRECT_APPLICATION_ENV in the list en variable. I understand why now. Thank you. For the rest, this Phalcon application will be port to Laravel. – Daniel Jan 15 '23 at 17:21

1 Answers1

0

Environment variables set with SetEnv in an htaccess file are available in the Apache environment, so you should use apache_getenv() or the $_SERVER superglobal to access the variable rather than getenv().

You appear to be using SetEnv correctly, and the rest of your setup looks fine.

Perhaps you may be interested in a .env file instead in your root directory, and using vlucas/dotenv to load it in, and use Dotenv in your code instead.

Here's an example of using that package:

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

It will look for an .env file in __DIR__ and load them into your environment, making them available via getenv()

zanderwar
  • 3,440
  • 3
  • 28
  • 46
  • There should be no problem using `getenv()` here. `apache_getenv()` is only available on systems where PHP is installed as an Apache module (and allows access to additional Apache server variables). If the env var is available in the `$_SERVER` superglobal then you should also be able to access it via `getenv()`. – MrWhite Jan 15 '23 at 16:57