How to work with environment variables in PHP?
Use getenv() to read environment variables and vlucas/phpdotenv to load .env files in development; store sensitive data like API keys outside code, never commit .env to version control, and use actual environment variables in production for security.
Working with environment variables in PHP helps keep configuration separate from code, especially for sensitive data like API keys or database credentials. The most common and secure way to handle them is through the .env file in development, while using actual environment variables in production.
Using getenv() and putenv()
PHP provides built-in functions to interact with environment variables.getenv() retrieves the value of an environment variable:
- getenv('HOME') returns the user's home directory. - getenv('APP_ENV') could return 'development' or 'production'.If no argument is passed, getenv() returns an associative array of all available environment variables.
putenv() and setenv() let you define or modify environment variables at runtime:
- putenv('API_KEY=abc123') sets a variable accessible via getenv('API_KEY').
- These changes are temporary and only last for the duration of the script.
Using a .env file in development
Most PHP projects use a .env file to manage environment variables locally.Create a .env file in your project root:
APP_ENV=developmentDB_HOST=localhost
DB_USER=root
DB_PASS=secret
API_KEY=your_api_key_here
To load this file, you can manually parse it or use a library like vlucas/phpdotenv, which is widely adopted.
Install it via Composer: composer require vlucas/phpdotenv
Then load the variables in your bootstrap script: $dotenv = Dotenv\Dotenv::createImmutable(DIR);\n $dotenv->load();
After this, you can access the values using getenv() or $_ENV.
Accessing variables via $_ENV and $_SERVER
Environment variables may also be accessible through superglobals, depending on PHP configuration.$_ENV contains environment variables if variables_order includes 'E' in php.ini.
$_SERVER often contains the same values (e.g., $_SERVER['DB_HOST']).
However, relying on $_ENV isn't always safe due to server configuration differences. getenv() is more consistent.
Best practices
To use environment variables safely and effectively: - Never commit .env files to version control. Add them to .gitignore. - Provide a .env.example file with dummy values for onboarding. - Validate required variables at startup. - Use actual environment variables (not .env files) in production for security.Basically, use getenv() to read, vlucas/phpdotenv to load from a file, and always keep secrets out of code.
The above is the detailed content of How to work with environment variables in PHP?. 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.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

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



The official download portal of Aisi Assistant is located on the official website https://www.i4.cn/, and provides computer and mobile downloads, supporting device management, application installation, mode switching, screen projection and file management functions.

The free ad-free entrance of Biquge 1v1 is https://www.biquge.info/. The platform covers novels of many themes such as urban and fantasy. It is updated in time, supports book titles and author searches, and has a popularity ranking. The reading interface is simple, and it can adjust the font, background and night mode. There are few advertisements and no interference, and the loading is smooth. It is suitable for mobile phones and PCs. You do not need to download the APP, and you can synchronize the bookshelf and reading records by logging in.

The entrance to the Little Red Book Dandelion can be accessed through the mobile app or computer. 1. Mobile: Open Xiaohongshu App, log in to an account that has completed real-name authentication, click "Me" to enter the personal center, find "Creation Center" or "Cooperation Center", click "More Services" and select "Blogger Cooperation" or "Dandelion Member" to enter; 2. Computer: Visit the official website https://in.xiaohongshu.com/, click "Login" in the upper right corner, and use the certified creator account to authorize login. The system automatically identifies the identity and enters the corresponding interface. New users need to submit their identity certificates, business licenses and other materials to complete their entry. The platform provides functions such as data analysis, blogger screening, cooperation management, content delivery and heating, and supports multiple cooperation modes.

The latest access address of Qushu.com downbook is https://downbook.cc/. The platform provides rich e-book resources, covering a variety of topics, supports customized reading settings, night mode, offline downloads and synchronized reading progress across devices, ensuring that users have a smooth and comfortable reading experience.

The latest version of Google Earth online access is https://earth.google.com/web/, which supports global high-definition satellite images, 3D terrain, street panorama and historical image backtracking. It can operate smoothly in the browser without downloading, and can synchronize collection and custom landmarks through your account.

Xuanshu.com’s latest address is https://www.xswang.com. The website provides a variety of novel resources, covering various themes such as urban and fantasy, and supports multi-terminal synchronization and personalized reading settings to ensure a smooth and comfortable reading experience.

selfreferstotheclasswhereitisdefined,ignoringinheritance;staticuseslatestaticbinding,callingmethodsfromtheruntimeclass.2.Useselfforearly-boundaccess,staticforlate-boundwhenoverridinginchildclassesisexpected.

First, back up the configuration and project data, then perform the new version overlay installation and manually migrate the data. Specifically: 1. Backup the config and projects folders; 2. After closing the program, custom installation to the original directory; 3. Copy the backup content to the new version data directory and verify whether the project and interface functions are normal.
