Why salt is stored inside .env file instead of inside php file?

Short answer - it's easier to keep one file safe than a whole source code archive or repository.

It's true - if a hacker gets into the server, it doesn't matter where you store the data. They'll likely get root access or at least gain access to whatever the application has access to including databases, env files, etc.

There are a few reasons to keep secrets in a different file from your source code.

  1. env is local to where the software is deployed. You might support many environments. Even as simple as local development and production.

  2. Source code is typically stored in a something like github where you check the files in. Even if not, there are usually multiple copies of the source files. Across computers, email, or dropbox.

    More copies of the source mean more people have access to the source code. More opportunities for that source code to end up in the wrong hands. Source code is less secure than the env file on the server.

  3. It's typically easier to keep one file secure that's out of the source code. For example, we encrypt vast amounts of data using a symmetric key. We know we must keep the key secret but are less worried about the encrypted data. We can replicate encrypted data across geographically separate data centers without concern of the transit protocols because we know we only need to keep the key safe.

    It's similar with the env file - it's the one thing you need to keep at a higher security level so that you can more freely share the source code with a team. If you were worried about having credential-type material in source code then you (or your security team) would be much more hesitant to share the code, thus impacting your ability to deliver business value.