Adding a simple authentication using PHP require and includes

Please note that this tutorial has now been superseded by a later, more in-depth tutorial available here

Continuing on with our to-do application, in this weeks snippet we’re going to be using PHP’s require_once function. The require_once function is similar to the require function, in that it will execute and include any php code with the calling file but with one vital difference. It will only execute once. This is important for us in this tutorial as we are going to use it to validate our user.

There are a few things to note first, since this is a short tutorial I will be doing something that is not a good idea in a production application. I will be storing the logged in state in the $_SESSION variable, this is only temporary as next week we will be updating it to store it in a MySQL database. We will also be storing in the database additional information such as the source IP address and a timestamp to mitigate against session hi-jacking.

Getting started

First we will need to convert our existing index.html file to a php file. To do this, simply change the extension to ‘.php’ and open the file in your text editor. We will now also create a new php file called ‘authenticate.php’ and save it in the same folder as our new index.php.

Now inside our index file, we are going to add the following php code to the very top of the file.

<?php
require_once('authenticate.php');
?>

This means that as soon as the file is executed, it will read and execute our authenticate.php file. The contents of the authenticate file is also pretty straight forward for now. We’re going to ensure our session has been started (session_start), and then check to see if the $_SESSION variable contains our authenticated flag. If it doesn’t exist or is not set to ‘true’ we will re-direct the user to our 3rd new page login.php. To perform the re-direct we are going to update the header Location value to point to our login.php file.

By also adding the above code to our submit.php, we can also ensure that only authenticated users can add tasks.

<?php
session_start();
if(empty($_SESSION["authenticated"]) || $_SESSION["authenticated"] != 'true') {
    header('Location: login.php');
}
?>

In the scenario where we have already logged in, the index.php file will continue to execute as normal and we shall see our form and table as usual.

Logging in

Next up, we are going to create our login page. For now, it will be just a simple username and password form that uses POST to send the provided details to itself.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title>Creating a simple to-do application - Part 1</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="page">
    <!-- [banner] -->
    <header id="banner">
        <hgroup>
            <h1>Login</h1>
        </hgroup>        
    </header>
    <!-- [content] -->
    <section id="content">
        <form id="login" method="post">
            <label for="username">Username:</label>
            <input id="username" name="username" type="text" required>
            <label for="password">Password:</label>
            <input id="password" name="password" type="password" required>                    
            <br />
            <input type="submit" value="Login">
        </form>
    </section>
    <!-- [/content] -->
    
    <footer id="footer">
        <details>
            <summary>Copyright 2013</summary>
            <p>Jonathan Schnittger. All Rights Reserved.</p>
        </details>
    </footer>
</div>
<!-- [/page] -->
</body>
</html>

At the top of this file we’re going to add our POST logic.

<?php
$username = null;
$password = null;

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    if(!empty($_POST["username"]) && !empty($_POST["password"])) {
        $username = $_POST["username"];
        $password = $_POST["password"];
        
        if($username == 'user' && $password == 'password') {
            session_start();
            $_SESSION["authenticated"] = 'true';
            header('Location: index.php');
        }
        else {
            header('Location: login.php');
        }
        
    } else {
        header('Location: login.php');
    }
} else {
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title>Creating a simple to-do application - Part 1</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="page">
    <!-- [banner] -->
    <header id="banner">
        <hgroup>
            <h1>Login</h1>
        </hgroup>        
    </header>
    <!-- [content] -->
    <section id="content">
        <form id="login" method="post">
            <label for="username">Username:</label>
            <input id="username" name="username" type="text" required>
            <label for="password">Password:</label>
            <input id="password" name="password" type="password" required>                    
            <br />
            <input type="submit" value="Login">
        </form>
    </section>
    <!-- [/content] -->
    
    <footer id="footer">
        <details>
            <summary>Copyright 2013</summary>
            <p>Jonathan Schnittger. All Rights Reserved.</p>
        </details>
    </footer>
</div>
<!-- [/page] -->
</body>
</html>
<?php } ?>

Here you can see that if the POST variable contains the keys username and password it will attempt to confirm that their values are equal to user and password. If they are not, it will redirect the user back to itself. If the values are correct, we ensure our session is started and set our ‘authenticated’ session value to true and then re-direct to our index.php file. I’ve also wrapped the HTML tags in a conditional statement, so that if the page is requested using a GET it will show the log in form as normal.

Since we have now setup our session and the authenticated flag has been set, the index page will render as normal.

A final note

As I have previously mentioned, this is not secure and should not be used in a production environment. It does however introduce us to session variables and allows us a stepping stone on to improving security and MySql database connectivity next week. In a later tutorial we will also be revisiting the require_once function to give us basic templating abilities for common HTML elements such as the header and footer of our application.

A battle hardened software developer with a mixed and colorful background, who can't come up with a decent author bio More articles by Jonathan Schnittger
Home CSS Deals DesignBombs HTML HTML5 JavaScript jQuery Miscellaneous Mobile MySQL News PHP Resources Security Snippet Tools Tutorial Web Development Web Services WordPress