In what situations would using .env files or environment variables be a more secure option for storing sensitive data in PHP applications?

Using .env files or environment variables is a more secure option for storing sensitive data in PHP applications because it allows you to separate configuration from code, reducing the risk of accidentally exposing sensitive information through version control or code leaks. Additionally, .env files are not accessible to the public, making it harder for attackers to access sensitive data. Using environment variables also allows for easy configuration management across different environments without exposing sensitive data.

// .env file
DB_HOST=localhost
DB_USER=root
DB_PASS=password

// PHP code to access environment variables
$host = getenv('DB_HOST');
$user = getenv('DB_USER');
$pass = getenv('DB_PASS');

// Connect to database using the retrieved credentials
$conn = new mysqli($host, $user, $pass);