HOWTO: Requiring a login with PHP/MySQL and Apache
misc

HOWTO: Requiring a login with PHP/MySQL and Apache

This tutorial will discuss how to require users to login before they are able to view the files in a given directory. This tutorial assumes you have PHP server-side scripting language and MySQL database server running on a Linux webserver using Apache HTTP Daemon as your webserver daemon and have a working knowledge of Apache virtual host containers, the PHP scripting language and MySQL databases.

Disclaimer: There are many ways of doing this, and this just happens to be mine. However, if you feel this script is in some way insecure or vulnerable to attack, please feel free to contact me and let me know. I do not take any responsibility for anything that happens as a result of following this tutorial so use this code at your own risk.

Important: If you need further help please try to find a forum or chatroom where someone can help you, as I will not respond to e-mails asking for more help then is provided here. This tutorial is provided as is, if it meets your needs then great. If not, I appologize, but will not provide further support. As always, RTFM.


Step 1 - Setting up apache:

First thing we need to do is set up our Apache vhost container to require a script to run before any file in our directory will be allowed to be viewed. This is done with PHP's auto_prepend_file feature. The following is an example <Directory> container which you should place within your <VirtualHost> container in Apache:

<Directory /system/path/to/directory>
    php_value auto_prepend_file /system/path/to/directory/prepend.php
</Directory>

(Be sure to replace /system/path/to/directory with the actual system path to the directory you wish to secure.)

Step 2 - Creating prepend.php:

Your prepend.php file should look like this:

<?
    $scriptname = '';
    if (isset($HTTP_SERVER_VARS['SCRIPT_NAME'])) {
        $scriptname = $HTTP_SERVER_VARS['SCRIPT_NAME'];
    }
    session_start();
    if (
        ($_SESSION['loggedin'] == FALSE) &&
        ($scriptname != "/login.php") &&
        ($scriptname != "/error.php") &&
        ($scriptname != "/logout.php")
    ) {
        include("require.php");
        exit();
    }
?>

Step 2 - Creating require.php and error.php:

You will need to create two files, require.php and error.php. The contents of these files is basically the same except that on error.php you will display an error message, as this is the page you send the user to should they input an incorrect username/password combination. You should format these to match the rest of your website. Your require.php file should look like this:

<p class="text">Please enter your username and password.</p>
<form method="post" action="http://www.website.com/directory/login.php">
<table cellpadding="4" cellspacing="0" border="0">
    <tr>
        <td>User Name</td>
        <td><input type="text" name="login_username" size="35" /></td>
    </tr>
    <tr>
        <td>Password</td>
        <td><input type="password" name="login_password" size="35" /></td>
    </tr>
    <tr>
        <td colspan="2" align="center">
        <input type="submit" value=" login " />
        </td>
    </tr>
</table>
</form>

Your error.php file should contain the same code, except instead of "Please enter your username and password." you should display an error message like "Sorry but that username/password is incorrect. Please try again."

Be sure to replace "www.website.com/directory" with the URL to your directory.

Step 3 - Creating login.php:

The login.php script will check the database and search for the supplied username/password in order to authenticate the user. Your login.php should look something like this:

<?
    // MySQL database
    $mysql_db = "";

    // MySQL hostname
    $mysql_host = "localhost";

    // MySQL username
    $mysql_user = "";

    // MySQL password
    $mysql_pass = "";

    // connect to the database
    $link = mysql_connect("$mysql_host", "$mysql_user", "$mysql_pass")
        or die("Could not connect to server");

    // select the database to use
    mysql_select_db("$mysql_db") or die("Could not select database");

    $username = '';
    if(isset($HTTP_POST_VARS['login_username'])) {
        $username = $HTTP_POST_VARS['login_username'];
    }

    $password = '';
    if(isset($HTTP_POST_VARS['login_password'])) {
        $password = $HTTP_POST_VARS['login_password'];
    }

    $query = mysql_query("SELECT username, password
        FROM users WHERE username = '$username'
        AND password = password('$password')") or die(mysql_error());

    $num_rows = mysql_num_rows($query);
    if ($num_rows == "0") {
        header("Location: http://www.website.com/directory/error.php");
        exit();
    } else {
        while(list($username) = mysql_fetch_row($query)) {
            session_start();
            $_SESSION['loggedin'] = TRUE;
            $_SESSION['username_auth'] = $username;
            header("Location: http://www.website.com/directory/index.php");
            exit();
        }
    }
    // Closing database connection
    mysql_close($link);
?>

Once again, be sure to replace the "www.website.com/directory" on lines 34 and 41 of login.php with the URL to your directory. Also, fill in the values for the variables mysql_db, mysql_host, mysql_user & mysql_pass with the correct values for your configuration so you can connect to the MySQL database which we will create in the next step. By the way, if you want to reference the user's username in the page after they've logged in, you can use the session variable $username_auth in your code.

Step 3 - Creating a users table in a MySQL database:

You will need to create a "users" table in the database you specified in the $mysql_db variable above (and will need to create the database itself if it does not already exist). The code to create the users table is as follows:

CREATE TABLE `users` (
  `users_pk` int(11) NOT NULL auto_increment,
  `username` varchar(255) NOT NULL default '',
  `password` varchar(255) NOT NULL default '',
  PRIMARY KEY  (`users_pk`),
  UNIQUE KEY `username` (`username`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Step 4 - Creating logout.php:

Your logout.php file is the file you will link your "Log Out" button to. It should contain the following:

<?
    session_unregister("loggedin");
    header("Location: http://www.website.com/directory/index.php");
    exit();
?>

Step 5 - Putting it all together:

After placing the above <Directory> container into your website's <VirtualHost> container you will need to restart the Apache HTTPD. Then place prepend.php, require.php, error.php, login.php and logout.php in the directory you'd like to secure. You should now find that when you try to browse to that directory you will be promted for your username/password before being allowed to continue.

<<back