r/PHPhelp • • Oct 22 '22

Solved PHP server security?

Hello everyone, I pray that you are all doing well.

You might have noticed that the title is a question, that's because I'm not really sure what exactly I'm looking for.

But you might, so here is what I'm specifically asking about.

When we create a database in phpmyadmin, we later go to our coding program and start writing this :

<?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "whatever the database name is"; $conn = mysqli_connect($servername, $username, $password, $dbname); Now clearly this is not secure. And someone told me once that the username and password should not be like this. But all the tutorials do this, so what's the correct thing to write? Thank you all in advance, have a good day/night 😁 The Lord be with you all and save you all your families and friends 🤍

8 Upvotes

26 comments sorted by

View all comments

2

u/kAlvaro Oct 22 '22

Tutorials do it for two reasons:

  • A tutorial needs to focus on the subject it wants to illustrate. Simple programs are simple.

  • Internet is riddled with terrible PHP tutorials (you can't imagine how bad!).

As almost everything in IT, this subject can get as complex as you want. Some organisations even use an external configuration server where applications grab the values from and authorised users are able to manage the secrets they've been granted access to. On the opposite side, storing credentials with the source code (and probably upload them to GitHub) is wrong in almost every sense even for personal pet projects.

To have something in between, I'd suggest to keep secrets in a text file, call it .env, ensure it doesn't get committed to version control (i.e. add it .gitignore) and use a library like symfony/dotenv or a Composer plugin like helhum/dotenv-connector to have the values available as environment variables.

$conn = mysqli_connect($_SERVER['DB_HOST'], $_SERVER['DB_USER'], $_SERVER['DB_PASSWORD'], $_SERVER['DB_NAME']);

2

u/dabenu Oct 23 '22

Be extra careful not to put a .env file in your webservers public directories! It'll just be visible as plain text.

2

u/kAlvaro Oct 23 '22

Good point!

A typical layout has a public directory that's exposed to the web server (e.g. /var/www/public/img/foo.jpg is mapped to https://example.com/img/foo.jpg) and .env is one level up (e.g. /var/www/.env).