Creating a Login File

Most websites developed with PHP contain multiple program files that will require access to MySQL and will thus need the login and password details. Therefore, it’s sensible to create a single file to store these and then include that file wherever it’s needed.

The login.php file:

<?php // login.php
$hn = ‘localhost’;
$db = ‘publications’;
$un = ‘username’;
$pw = ‘password’;
?>

Type the example, replacing username and password with the values you use for your MySQL database.

The hostname localhost should work as long as you’re using a MySQL database on your local system, and the database publications should work if you’re typing the examples I’ve used so far 🙂
The enclosing tags are especially important for the login.php file,

because they mean that the lines between can be interpreted only as
PHP code. If you were to leave them out and someone were to call up the file directly from your website, it would display as text and reveal your secrets. But, with the tags in place, all that person will see is a blank page. The file will correctly include your other PHP files.

The $hn variable will tell PHP which computer to use when connecting to a database. This is required because you can access MySQL databases on any computer connected to your PHP installation, and that potentially includes any host anywhere on the web. However, the examples in this chapter will be working on the local server.

The database we’ll be using, $db, is the one called publications that we created earlier.

Another benefit of keeping these login details in a single place is
that you can change your password as frequently as you like and
there will be only one file to update when you do, no matter how
many PHP files access MySQL.

Leave a Reply

Your email address will not be published. Required fields are marked *