Building Browsergames: Using Configuration Files (PHP)
One of the things that you will encounter while building a Browsergame is the fact that you need to connect to a database. There’s just no way around it – if you plan to store the amount of data that a browsergame needs, you will need a database or some sort of storage layer in order to keep it all in one central location.
And each time you connect to the database, no matter how you do it, you will need to pass in the settings to connect to the database.
At the moment, we only have a basic registration page set up, so that’s not really a big deal. But what happens when you have a sprawling browsergame, spread out accross 75+ pages, and you suddenly need to change your database password?
It becomes a bit of a pain, that’s what. And that’s why you can benefit from using what’s known as a configuration file to store any information like database settings that you’ll need to refer to from multiple pieces of code.
If you want to use a configuration file in PHP, one of the easiest ways is to just create a file that sets some variables, and then just use the require_once() function to include it into your script. Here’s what a typical PHP configuration file would look like:
<?php $dbhost = 'localhost'; $dbuser = 'user'; $dbpass = 'password'; $dbname = 'db_name'; ?>
And then to use the above configuration file inside your PHP code, you would save the file as config.php, and then add the line below to any code you wanted to have use that configuration file:
And then, within your main code(whatever it might be), you could refer to $dbhost and all the other configuration variables as if you had set them within your code already. Here’s what it might look like in our registration page code:
require_once 'config.php'; $conn = mysql_connect($dbhost,$dbuser,$dbpass) or die ('Error connecting to mysql');
And that’s all there is to it! Now your database settings will be stored in just the one central area, and updating them will be a breeze.