Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Using .htaccess to access environment variables in PHP

If you’re working with the latest frameworks, it’s not very difficult to set up environment variables for your app.

For instance, Laravel uses the .env file to give you the ability to set the environment variables for your application.

So if you set below in the .env file…

APP_ENVIRONMENT="production"

…you can access it in the Laravel application like so.

'production' => env('APP_ENVIRONMENT', false),

But what if you want to set environment variables for the projects that use plain PHP? Read on.

Using .htaccess in Apache webserver

To define environment variables in the PHP app running on the Apache webserver, you can use the .htaccess file for this purpose. For this, all you need to enable the mod_env module in your server. You can enable using the following command.

$ sudo a2enmod env

Once done, you’ll then need to restart the server.

After this, if you want to set an environment variable called APP_ENVIRONMENT, you can add the following lines into your .htaccess file of your project like so.

<IfModule mod_env.c>
    SetEnv APP_ENVIRONMENT production
</IfModule>

You can define as many environment variables as you may like in the same block.

To access this environment variable in your PHP application, you can use $_SERVER global array like so.

$appEnv = $_SERVER['APP_ENVIRONMENT'];
Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?