


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)

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 referrals table to record recommendation relationships, including referrals, referrals, recommendation codes and usage time; 2. Define belongsToMany and hasMany relationships in the User model to manage recommendation data; 3. Generate a unique recommendation code when registering (can be implemented through model events); 4. Capture the recommendation code by querying parameters during registration, establish a recommendation relationship after verification and prevent self-recommendation; 5. Trigger the reward mechanism when recommended users complete the specified behavior (subscription order); 6. Generate shareable recommendation links, and use Laravel signature URLs to enhance security; 7. Display recommendation statistics on the dashboard, such as the total number of recommendations and converted numbers; it is necessary to ensure database constraints, sessions or cookies are persisted,

Table of Contents Market Interpretation of the concentrated shipment of ancient giant whales, BTC prices quickly repair ETH close to $4,000 key position, polarization of pledge and fund demand, altcoin sector differentiation intensifies, Solana and XRP funds inflows highlight market hotspots pay attention to macro data and policy trends, and market fluctuations may intensify last week (July 22-July 28). BTC maintained a high-level oscillation pattern. The ETH capital inflow trend continues to improve, the ETH spot ETF has achieved net inflow for eight consecutive weeks, and the ETH market share has climbed to 11.8%. On July 25, affected by the massive selling of Galaxy Digital, BTC fell below $115,000 for a short time, reaching the lowest point

SetupLaravelasanAPIbackendbyinstallingLaravel,configuringthedatabase,creatingAPIroutes,andreturningJSONfromcontrollers,optionallyusingLaravelSanctumforauthentication.2.ChoosebetweenastandaloneReactSPAservedseparatelyorusingInertia.jsfortighterLaravel

Use FormRequests to extract complex form verification logic from the controller, improving code maintainability and reusability. 1. Creation method: Generate the request class through the Artisan command make:request; 2. Definition rules: Set field verification logic in the rules() method; 3. Controller use: directly receive requests with this class as a parameter, and Laravel automatically verify; 4. Authorization judgment: Control user permissions through the authorize() method; 5. Dynamic adjustment rules: dynamically return different verification rules according to the request content.

Directory NaorisProtocol Project Position NaorisProtocol Core Technology NaorisProtocol (NAORIS) Airdrop NAORIS Token Economy NaorisProtocol Ecological Progress Risk and Strategy Suggestions FAQ Summary of FAQ NaorisProtocol is a decentralized Security-as-a-Service framework aimed at using a community-driven approach to conduct continuous auditing and threat detection of blockchain networks and smart contracts. "Security Miner" participated by distributed nodes

DanglingimagesareuntaggedlayersnotassociatedwithanycontainerandcanberemovedusingDocker’sbuilt-incommands.1.Usedockerimageprunetosafelyremovedanglingimagesafterconfirmation,oradd-ftoforceremovalwithoutprompt.2.Usedockerimageprune-atoalsoremoveallunuse

Identifying and exploring potential assets in the crypto field requires a four-step method: 1. Capture market signals such as social media topic growth rate, growth of ecological interaction address number, and mainstream platform search index; 2. Verify fundamentals such as team background, rationality of token model, and distribution of on-chain coin address; 3. Combined with technical indicators such as weekly breakthroughs in key resistance levels, trading volume exceeds 3 times per month, and RSI is in the 40-60 range; 4. Establish a continuous tracking mechanism for data dashboard monitoring, project milestone reminders and development progress review, and beware of traps such as abnormal promotion, liquidity pool imbalance and lack of technical documents, and optimize decision-making through small-scale testing, establishing tracking lists and retaining 20% cash reserves, and ultimately relying on in-depth research rather than chasing hot spots to achieve long-term success.
