After I posted parts 1-3 on reddit, I got chided for poor security implementation and using out of date code. I’m going to share what I learned about PHP best practices as well as make some security improvements to my previous code. First, let’s go over why what I did before was kind of bad.
First off, I’m using the mysql_ functions here to do everything. I did not realize that these functions were depreciated several years ago, and that they should probably no longer be used. I’ve updated this file now using PDO, or PHP Data Objects. Luckily, this required no additional configuration of my web server, and if you followed my installation process you should be set with this too. You can easily check by opening a web browser and going to https://localhost/dashboard/phpinfo.php, then searching for PDO to see if you have the proper drivers installed. Anyways, here’s the above script using PDO:
You’ll notice that all the mysql_ functions are gone and have been replaced. Instead, we use the “new PDO($dsn, $username, $password)” to log into our database server. Instead of sending a direct query, we prepare a query statement and then bind the necessary parameters into it. Doing this should automatically sanitize our user input as well.
You may also notice that there’s an extra step that is being taken now, and that is hashing our user’s password before inserting it into our database. To do this, I’m using password_hash(), a built-in PHP function that automatically generates a salt and hashes our user’s password. Let’s take a look at our GetUser.php script using PDO functionality:
Once again, we are using a PDO to log in to our database and preparing a query statement. This time, we also need to use the data that comes back from our MySQL server, so we use the fetch() statement to retrieve the data after executing our statement. The data that we are concerned with is for now just the user’s password. We then user password_verify() to verify that our user’s attempted password entry is correct before outputting a simple text string. This means that we aren’t exposing any of our users’s data, unlike in the old version where we verified our users passwords in Unity and exposed the password to the world.
The best part about all of this code is that we don’t even really have to change anything about our code in Unity! Only some small changes are needed in DatabaseConnection.cs to replace the PostLoginAccount() function, as we now need to send the user’s password attempt to our server:
And that’s it! This solution should be infinitely more secure than previously and the only things that really needed to be changed was the PHP files running on your server.