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.

Author: Jonathan Schnittger
A battle hardened software developer with a mixed and colorful background, who can't come up with a decent author bio
  • http://www.viditkothari.co.in/ Vidit Kothari

    the 2nd Code section has an error:
    The string value for the header() function needs to be closed with single quotes (‘).
    i.e. from the 2nd line, the code should be:

    header(‘Location: login.php’);
    }
    ?>

    • Jonny Schnittger

      Thanks, didn’t spot that. The demo doesn’t have the same issue… I must have deleted somehow. Good catch :)

  • http://www.yepi2.info/ yepi2

    Thank you for sharing meaningful information

  • http://yepi-games.kizifriv1.com/ Yepi Friv

    I appreciate your enthusiasm and dedication in writing this article. Very nice work.

  • ccornutt

    By the way, for anyone reading this article that didn’t get it – please, please *please* do not hard-code passwords into your code like this. I understand this is for illustration purposes, but it is a very bad practice and should always be avoided. Please use some sort of external data source (preferably some kind of hashed/salted password storage method) to keep user information out of your code.

    Copy and pasting this code into your application is a very bad idea.

    • Jonny Schnittger

      Indeed, I think I was pretty clear on that. The full tutorial today will expand on that and introduce MySql and creating tables. One of the tables will be a user table, just for this purpose.

    • Jonny Schnittger

      I’ve published todays post that improves on the security of the application and added a note to the top of this one. I hope to cover form submission and nonce validation in one of the upcoming snippets

  • http://www.frivk.com/ Friv 4 School

    . I know no article is perfect, but yours is as close as it gets. Good job.

  • http://www.biztechconsultancy.com/php-development-india.htm php development india

    I like the way of describing this post. very crucial and useful post it is. Good work.

  • http://www.jugarfriv.org/ friv

    I Use php. Thanks for share

  • http://www.sasasoftwaretechnologies.com/ Web Development Company

    Great article and a big thanks for sharing your experience!

  • Bane

    Nice tut +1

  • kamilah27

    F2h – The Last years i would be down on money and debits were killing me from everywhere. That was UNTIL I learned to make money on the INTERNET! I landed on surveymoneymaker period net, and started filling in surveys for cash, and really, i have been really more able to do my things!! i’m so glad, I did this.. With all the financial stress these years, I really hope all of you will give it a chance. – C7e