Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

stocksph's avatar

Database access details on .env file exposed/vulnerable

Hi,

    I set my correct database config at config/database.php file then I run my laravel app
    then it says "SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES)"
    
    I noticed that it uses the db config file on .env file
    and when I set my database access to .env file it works but the real problem 
    lies here the .env is exposed like when I visit http://localhost/laravel/.env it gives visitors the 
    full details of my database access.

    Is there a way to secure it? Or did I missed something?

    Any help is highly appreciated.

Sincerely, John

0 likes
8 replies
tomopongrac's avatar

.env file should not be in public directory. On server only public directory should be available for visitors

all the files and folders above public must not be accessible.

tomopongrac's avatar

no, your laravel app is located in http://yourdomain.com which is located in public directory on server

in apache server you must have documentroot to "your/path/to/laravel/public"

stocksph's avatar

I see. thanks for providing it.

Just one last question, I was wondering why setting up the database access on config/database.php dont matter on .env file?

I mean the final access that will accept by laravel app is the access on .env file.

any help is highly appreciated.

tomopongrac's avatar

You must in cofig file provide env variables like this

'sqlsrv' => [
    'driver' => 'sqlsrv',
    'host' => env('DB_HOST', 'localhost'),
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    'charset' => 'utf8',
    'prefix' => '',
],

https://laravel.com/docs/5.2/database

pmall's avatar

Laravel is not made to be put in a subdirectory. There must be a vhost with a root pointing to /public thats all.

stocksph's avatar

@tomo, if i set the config file, will it automatically set the right access on .env? coz right now it doesnt. im using laravel 5.2

at the moment, if i set the config file on config/database.php i also need to set the same access on .env

any insights?

tomopongrac's avatar

Try this in config file

'driver' => 'sqlsrv',
    'host' => getenv('DB_NAME'),
    'database' => getenv('DB_DATABASE'),
    'username' => getenv('DB_USERNAME'),
    'password' => getenv('DB_PASSWORD'),

and set values in .env file

Please or to participate in this conversation.