With regards to PHP security are .env files essential or even necessary

I have been told that for enhanced security, variables for sensitive info such as database credentials should be stored in a .env file. This is a new concept to me and I am unfamiliar with .env files. Should I consider using them?
Thanks

I dont know that .env files in particular are more or less secure than regular variable declarations, but said variables should be kept in a file outside of the document root, which may be where the principle lies.

2 Likes

Cheers1

If you are unfamiliar with .env files, then you might be familiar with .ini files. They serve a similar purpose: to separate your code from your configuration.

This makes your code more portable. For example, you can send the code to someone else and they just need to edit the .ini or .env, not the PHP.

In terms of security, yes, this configuration can and often does include sensitive info like database credentials, API keys, and so on.

If so, for security, put the file outside of the document root and make it readable by PHP (but not the web server) or your credentials can be exposed.

A strength that .ini has over .env is that .ini supports creating groups of settings, whereas .env is a flat list and you have to prefix everything.

A strength that .env has over .ini is that if your script runs in the command line, you can override the default .env vars at runtime.

You could also use them together: specify in an env var what ini you want to load (production, testing, or development).

Using .env or cache is more of where they are stored than how you store the db credentials IMO. Using cache could easily be deleted together when the session is ended.

How does this differ from a separate PHP include file please, and . . .

Can you please give me any pointers or clues how to do this on an Apache Linux server. Thanks

On the server there is usually a folder which contains all the publically accessible files. Its name may vary, could be htdocs, httpdocs, public_html, html, public, or whatever. It’s usally the place you find .htaccess and your index/home.html/php files along with sub-folders for images, scripts, css, etc. The root of the public site.
You can however create another folder along-side it (a sibling folder, not a child), call it private or whatever you want, the important thing is it’s not within the public root folder which can be accessed from the outside.
I tend to put all PHP files away like this, with the exception of the public index.php which is just an entry point that does nothing but require the router script, but I digress.

A separate PHP include file can serve that purpose as well. Just don’t include it in your version control with the other PHP scripts.

1 Like