-1

I am developing a little website project for a cybersecurity course. What is the best practice for utilizing mysqli_real_connect on a PHP document?

Is writing the db credentials directly as arguments of the function a good way to go or should I pass them in a different way?

P.S. The user can't see the source code, but I am trying to see if there are security aspects which I am overlooking.

TheEncoder
  • 58
  • 6
  • 1
    use pdo or mysqli mysql is outdated and deprecated. see https://phpdelusions.net/pdo#prepared if you want to learn all about pdo – nbk Mar 19 '21 at 17:38

1 Answers1

1

Storing database credentials in your source code is always a terrible idea. Do not do it. If you have credentials in your code, you have a problem that needs to be resolved.

You must store your credentials somewhere that is not in the web root of your application so that even if our server is badly misconfigured they won't leak out.

You say that "the user can't see the source code", but this is an assumption that is often mistaken. A botched config can disable PHP, rendering .php files as plain-text visible to the user. If you have an index.php with credentials in it, you've just leaked those. You can also misconfigure your server with .phps support enabled inadvertently, meaning anyone can ask for the source of any page and get it, complete with pretty syntax highlighting!

You can also have situations where a SQL injection bug allows an attacker to start downloading arbitrary files from your server. If this is the same server as your PHP application you're really in bad shape. Maintaining separation between database and application can help considerably here. Keep them deployed on two different virtual machines or containers.

Look at how frameworks recommend you configure them. Typically there's a separate config directory that isn't even stored in your version control system, you don't want credentials there either.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • Good answer! It doesn't even have to be a botched configs though. Web servers are software. Software has bugs. Certain conditions can make the web server not handle php-files properly. – M. Eriksson Mar 19 '21 at 17:43
  • 1
    @MagnusEriksson It's true, there's been a few rather alarming bugs that have allowed people to grab the source without authorization. It's best to assume that some day that "source" will leak, which is why most frameworks have a boring old `index.php` and absolutely nothing more in that web root. – tadman Mar 19 '21 at 17:44
  • Apache under some serious load can also start acting erratic. And I agree. If you follow the [front controller pattern](https://en.wikipedia.org/wiki/Front_controller) (which majority of semi-modern to modern frameworks/applications does), it's easy. – M. Eriksson Mar 19 '21 at 17:46
  • 1
    @MagnusEriksson I don't judge. We all do. – tadman Mar 19 '21 at 17:47
  • I hear that! ;-) – M. Eriksson Mar 19 '21 at 17:49