


How to set environment variables in PHP environment Description of adding PHP running environment variables
Jul 25, 2025 pm 08:33 PMThere are three main ways to set environment variables in PHP: 1. Global configuration through php.ini; 2. Passed through a web server (such as SetEnv of Apache or fastcgi_param of Nginx); 3. Use putenv() function in PHP scripts. Among them, php.ini is suitable for global and infrequently changing configurations, web server configuration is suitable for scenarios that need to be isolated, and putenv() is suitable for temporary variables. Persistence policies include configuration files (such as php.ini or web server configuration), .env files are loaded with dotenv library, and dynamic injection of variables in CI/CD processes. Security management sensitive information should be avoided hard-coded. It is recommended to use .env files with .gitignore, Docker Secrets, or cloud services such as AWS Secrets Manager. If the environment variable does not take effect, you should check the PHP operation mode, confirm the variable scope, verify the configuration file path, and whether to restart the service.
There are usually several core ways to set environment variables in a PHP environment: globally set up the php.ini
configuration file, pass it using the configuration of a web server (such as Apache or Nginx), or use the putenv()
function directly inside a PHP script. Which method you choose often depends on your PHP operation mode, the isolation requirements of your environment, and the life cycle of the variables.

Solution
To be honest, PHP environment variables sound a bit mysterious, but they are actually quite straightforward to use. I personally think that the most common and safest way is nothing more than just a few, each with its own applicable scenarios, and none of them is a "universal solution".
First of all, the most direct thing is to change php.ini
. You can directly use variables_order
or E
in the file to control which variables can be accessed by PHP. However, the more commonly used configurations are configurations like upload_max_filesize
. They are PHP configuration items and are not quite the same as environment variables at the operating system level. But if you want a certain environment variable to take effect globally, such as database connection information, or API key, it is a way to use env[VAR_NAME] = value
in php.ini
. But there is a problem with this, that is, if you change php.ini
, you need to restart PHP-FPM or web server, and this will affect all applications running in this PHP environment and are not flexible enough.

Then it is through the web server. If you use Apache, the SetEnv
directive is in the .htaccess
file or the Apache configuration file, it is simply a magic tool. for example:
<IfModule mod_env.c> SetEnv APP_ENV "production" SetEnv DATABASE_URL "mysql://user:pass@host/db" </IfModule>
This thing is good, it can be effective for specific directories or virtual hosts, and the isolation is done well. For Nginx, you have to use fastcgi_param
, usually in the fastcgi_params
file or your server block:

fastcgi_param APP_ENV "development"; fastcgi_param DATABASE_URL "mysql://user:pass@localhost/dev_db";
Both methods are considered to inject environment variables from the Web server layer into the PHP process. PHP scripts can be obtained through $_SERVER
or getenv()
. I personally prefer this method because it separates the configuration and code, and it also facilitates the injecting different environment configurations into the CI/CD process.
Finally, of course, putenv()
inside the PHP script. This function allows you to set an environment variable at runtime.
<?php putenv("MY_CUSTOM_VAR=hello_world"); echo getenv("MY_CUSTOM_VAR"); // Output: hello_world ?>
But to be honest, I rarely use it to set critical environment variables that need to be available throughout the request lifecycle. It is more used in some temporary scenarios that are only used by the current script or child process. Because the variables it sets are only valid for the current PHP process, they are gone after the request is completed and cannot affect the parent process.
To sum up, which one to choose depends on your needs. Global and invariant, php.ini
or web server configuration; if it needs to be isolated, the web server configuration is better; if it is temporary, internally used by scripts, putenv()
.
What are the persistence strategies for PHP environment variables?
When it comes to persistence, this is not a simple question, because the word "persistent" has different interpretations in different contexts. What I understand persistence is to allow environment variables to maintain their value outside the PHP process lifecycle, or at least automatically load every time a new request arrives.
The most direct persistence is of course writing variables into the configuration file. For example, php.ini
mentioned just now, or the configuration file of the web server (Apache's httpd.conf
or Nginx's nginx.conf
). Once these files are set up, these variables will always exist as long as the server does not restart, or the PHP-FPM process is not killed. This is the most "hardcore" persistence. However, the disadvantages are also obvious. The changes require restart of the service, and they are not flexible enough to be suitable for multi-environment deployment.
Another common "persistence" method is actually a philosophical manifestation of "convention is greater than configuration", that is, .env
files. Although PHP itself does not directly recognize .env
files, through libraries like vlucas/phpdotenv
, you can load these files at the start of the application.
// composer.json // "require": { // "vlucas/phpdotenv": "^5.0" // } // public/index.php or bootstrap file $dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/../'); // Point to your project root directory $dotenv->load(); // After that you can access these variables through getenv() or $_ENV $dbHost = getenv('DB_HOST');
The advantages of this method are:
- Environment isolation: Different environments (development, testing, production) can have different
.env
files, or use environment variables to specify which.env
to load. - Security:
.env
files are not usually submitted to the version control system (Git), thereby avoiding leakage of sensitive information. - Flexibility: Only replace the
.env
file during deployment can switch configurations without modifying the code or restarting the service (for PHP-FPM mode).
Personally, I can’t do without .env
in projects, especially modern PHP frameworks (such as Laravel and Symfony). It decouples the application configuration and code very well and conforms to the configuration principles of Twelve-Factor App.
There is another type, although not entirely "persistent", but it is very critical to the deployment process, that is, environment variable injection in CI/CD systems. For example, in GitHub Actions, GitLab CI or Jenkins, you can inject sensitive information as environment variables into containers or deployment targets during the build or deployment stage. These variables are injected at runtime and are not stored in the code library, which is extremely safe.
Therefore, the choice of a persistence strategy ultimately depends on your security needs, deployment processes, and team collaboration habits. There is no silver bullet, only the solution that suits you the most.
In PHP development, how to safely and effectively manage sensitive configuration information?
Managing sensitive configuration information is a big pit in any development, and PHP is no exception. I've seen too many projects that directly write database passwords and API keys in code, which is simply a security nightmare. To manage these things safely and effectively, my experience is that the core principle is "don't expose sensitive information directly to the code base."
The most basic thing, as I mentioned earlier, is to use .env
files to cooperate with .gitignore
. This is the easiest and most common practice. Your config.php
or framework configuration loading logic will read these variables instead of hard-code the values directly.
# .env file example APP_KEY=SomeRandomStringGeneratedByFramework DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=my_app DB_USERNAME=root DB_PASSWORD=secret
Then, remember to add .env
to .gitignore
:
# .gitignore .env
This way, your sensitive information will not be pushed to the public repository along with the code. Of course, this requires you to manually create or copy .env
files when deployed, or do it through automated scripts.
Going further, for more advanced scenarios, especially containerized deployments (such as Docker), I highly recommend using Secrets management . Docker Swarm has its own Secrets management mechanism, and Kubernetes also has Secrets objects. These mechanisms allow you to store and distribute sensitive data in an encrypted manner and are exposed to the application only when the container is running. For example, in Docker Compose, you can define secrets:
# docker-compose.yml version: '3.8' services: app: image: my_php_app Secrets: - db_password Secrets: db_password: file: ./db_password.txt # This is a file containing a password and is not usually submitted to Git
Inside PHP applications, these secrets are mounted as specific paths to the container as files, and your application can read these files to obtain sensitive information. This approach is safer than .env
files, because sensitive data won't even appear in plaintext in the file system (at least at the host level).
For cloud services, such as AWS, GCP, and Azure, they all have their own key management services (KMS). AWS has Secrets Manager, and GCP has Secret Manager. These services can help you centrally manage, audit and rotate keys. Your PHP application can get these keys dynamically at runtime through the SDK instead of hard-coded or stored in any file. This is undoubtedly the highest level of security practice, especially suitable for large-scale and multi-service distributed systems.
Finally, I want to emphasize one thing: never trust clients. Any sensitive information that needs to be passed to the front end should be proxyed or processed through the backend API, rather than being directly exposed. For example, you must not use Stripe's API key directly on the front end, but you should let the backend server call the Stripe API, and the front end only interacts with your backend API.
In general, from simple .env
to complex cloud KMS, which solution to choose depends on your project size, security requirements and operation and maintenance capabilities. But in any case, withdrawing sensitive information from the code base is the first and most critical step.
PHP environment variables are not effective? Frequently Asked Questions and Debugging Tips
It is quite annoying to encounter PHP environment variables that do not take effect, but there are usually traces to follow. My personal experience is that this kind of problem is often not a problem with PHP itself, but a deviation in environment configuration or understanding.
-
Check PHP running mode: This is the easiest to be ignored. In what mode does your PHP run? Is it Apache's
mod_php
? Or is PHP-FPM combined with Nginx/Apache? Or CLI mode?-
mod_php
(not recommended): Environment variables are usually passed directly by Apache configuration (SetEnv
). - PHP-FPM: Environment variables are usually passed by
fastcgi_param
in Nginx/Apache, or are set in the pool configuration of PHP-FPM (www.conf
, etc.). If you setfastcgi_param
in Nginx but don't get it in PHP, check whether the Nginx configuration is loaded correctly and whether the PHP-FPM is restarted correctly. - CLI mode: At this time, the PHP process directly inherits the shell's environment variables. You can set it with
export VAR=value
in the terminal, and thenphp your_script.php
. But if you are running scripts incrontab
, remember that the environment variables ofcrontab
are independent and may need to be explicitly set incrontab
entry.
-
-
Confirm the source and scope of the environment variable: Where did you set the environment variable?
-
php.ini
: Make sure you modify thephp.ini
file that is being used by the current PHP version. You can viewLoaded Configuration File
throughphpinfo()
. After modification, be sure to restart PHP-FPM or web server . - Web server configuration:
-
The above is the detailed content of How to set environment variables in PHP environment Description of adding PHP running environment variables. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Using the correct PHP basic image and configuring a secure, performance-optimized Docker environment is the key to achieving production ready. 1. Select php:8.3-fpm-alpine as the basic image to reduce the attack surface and improve performance; 2. Disable dangerous functions through custom php.ini, turn off error display, and enable Opcache and JIT to enhance security and performance; 3. Use Nginx as the reverse proxy to restrict access to sensitive files and correctly forward PHP requests to PHP-FPM; 4. Use multi-stage optimization images to remove development dependencies, and set up non-root users to run containers; 5. Optional Supervisord to manage multiple processes such as cron; 6. Verify that no sensitive information leakage before deployment

Laravel's configuration cache improves performance by merging all configuration files into a single cache file. Enabling configuration cache in a production environment can reduce I/O operations and file parsing on each request, thereby speeding up configuration loading; 1. It should be enabled when the application is deployed, the configuration is stable and no frequent changes are required; 2. After enabling, modify the configuration, you need to re-run phpartisanconfig:cache to take effect; 3. Avoid using dynamic logic or closures that depend on runtime conditions in the configuration file; 4. When troubleshooting problems, you should first clear the cache, check the .env variables and re-cache.

The real use of battle royale in the dual currency system has not yet happened. Conclusion In August 2023, the MakerDAO ecological lending protocol Spark gave an annualized return of $DAI8%. Then Sun Chi entered in batches, investing a total of 230,000 $stETH, accounting for more than 15% of Spark's deposits, forcing MakerDAO to make an emergency proposal to lower the interest rate to 5%. MakerDAO's original intention was to "subsidize" the usage rate of $DAI, almost becoming Justin Sun's Solo Yield. July 2025, Ethe

Create a seeder file: Use phpartisanmake:seederUserSeeder to generate the seeder class, and insert data through the model factory or database query in the run method; 2. Call other seeder in DatabaseSeeder: register UserSeeder, PostSeeder, etc. in order through $this->call() to ensure the dependency is correct; 3. Run seeder: execute phpartisandb:seed to run all registered seeders, or use phpartisanmigrate:fresh--seed to reset and refill the data; 4

EagerloadingpreventstheN 1queryproblembyloadingrelationshipsupfront.TheN 1problemoccurswhen1queryfetchesrecords(e.g.,100posts)andNadditionalqueriesfetchrelateddata(e.g.,authorforeachpost),resultingin101queries.Eagerloadingfixesthis:1queryretrievesall

The use of warehousing mode is to separate data access logic from business logic. 1. Define the warehousing interface and clarify the data operation method; 2. Create specific implementation classes based on Eloquent encapsulate database queries; 3. Use warehousing interfaces through dependency injection in the controller; 4. Bind interfaces and implementation classes in the service provider; ultimately implement code decoupling, improve testability and maintainability, and is suitable for scenarios where medium and large applications or require flexibly switching data sources.

LaravelSailisacommand-lineinterfacethatsimplifiesLaraveldevelopmentusingDockerbyprovidingapre-configuredenvironmentwithoutrequiringDockerexpertise;iteliminateslocalsetupconflicts,supportsconsistentteamenvironments,andenablesquickprojectinitialization

CheckPHP>=8.1,Composer,andwebserver;2.Cloneorcreateprojectandruncomposerinstall;3.Copy.env.exampleto.envandrunphpartisankey:generate;4.Setdatabasecredentialsin.envandrunphpartisanmigrate--seed;5.Startserverwithphpartisanserve;6.Optionallyrunnpmins
