PHP Introduction | Page Transitions, Cookies, and Sessions | Login Using Sessions

Now let us actually use sessions. Here, we will implement a login feature, which can be considered one of the most basic uses of sessions. Properly storing usernames and passwords in a database is still a little difficult at this point, so first we will prepare those values as variables inside the PHP script and only check against them.

Here, we will create two pages: index.php, the login page, and index2.php, the page displayed after login. First, write the login page, index.php, as follows.

<?php
    @session_start();
     
    if ($_POST != null){
        $account = $_POST['account'];
        $pass = $_POST['pass'];
        $_SESSION['account'] = $account;
        $_SESSION['pass'] = $pass;
        header("Location: ./index2.php");
    }
?>
<!DOCTYPE html>
<html lang="ko">
    <head> 
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
        <title>sample page</title>
    </head>
    <body>
        <h1>Hello PHP!</h1>
        <p>
            <?php
            if (isset($_SESSION['account'])) {
                echo "your account:" . htmlspecialchars($_SESSION['account']);
            }   
            ?>
        </p>
        <hr>
        <form method="post" action="./index.php">
            ACCOUNT :<input type="text" name="account"><br>
            PASSWORD:<input type="password" name="pass"><br>
            <input type="submit" value="Move">
        </form>
        <hr>
    </body>
</html>

When the form is submitted here, the script at the top checks its contents and stores them in the session. This by itself does not perform a login check. It simply stores the submitted account and password.

At the beginning, session_start is executed, with @ attached before it. This is the same symbol that appeared earlier during file access, meaning “ignore errors and continue.” Depending on the server, the session feature may already be ON by default. In that case, trying to start the session again may cause an error saying it has already started. This is a preventive measure for that.

$account = $_POST['account'];
$pass = $_POST['pass'];
$_SESSION['account'] = $account;
$_SESSION['pass'] = $pass;

Session-related processing is very simple. If you store values in $_SESSION, they are saved. It is simple enough that no other explanation is needed. One more part to mention is the script in the body that displays the current account. It is written as follows.

if (isset($_SESSION['account'])) {...omitted...

The isset function checks whether the variable specified as its argument exists. In other words, this checks whether $_SESSION['account'] exists.

Displaying a Page Only When Logged In

Next, let us write index2.php. Here, we will check whether the user is logged in and display the page only when login has succeeded. Write the example code as follows.

<?php
    @session_start();
     
    // ACCOUNT and PASS
    $ok_account = "admin";
    $ok_pass = "kanri";
     
    // Login check
    $flg = false;
    $account = $_SESSION['account'];
    $pass = $_SESSION['pass'];
    if ($account == $ok_account and $pass == $ok_pass){
        $flg = true;
    }
    // Processing when not logged in
    if (!$flg){
        echo "<html><body><h1>NOT LOGIN!!!</h1>";
        echo '<a href="./index.php">back to login page.</a>';
        echo "</body></html>";
        exit;
    }
?>
<!DOCTYPE html>
<html lang="ko">
    <head> 
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
        <title>sample page</title>
    </head>
    <body>
        <h1>Index2.php!</h1>
        <p>[Account: <?php echo htmlspecialchars($account); ?>]</p>
        <p>This is a newly prepared page.</p>
        <hr>
    </body>
</html>

Here, after first running @session_start, the registered user’s account and password are prepared in $ok_account and $ok_pass. Then the account and password values are each obtained from $_SESSION, the values are checked, and if the account and password match, true is assigned to the variable $flg. This variable indicates whether login succeeded. If it is true, the user is logged in; if it is false, the user is not.

If the user is not logged in, an error message and a link back to index.php are displayed with echo, and finally exit is executed. This means “terminate script execution here.” When exit is executed, all code after that is not executed. Not only PHP scripts but also the HTML code written afterward will not be output. In other words, if the user is not logged in, the page included here itself is not displayed.

Here, the response is handled by writing an error with echo and executing exit, but there are many ways to do it. Redirecting to an error page or returning to the login page would also be fine. Think about various other possible methods.

Generalizing Login Checks

This now makes the page display only when the user is logged in. However, if you have to write this processing on every page, login checking becomes inefficient. In such cases, you can prepare a login check page and load and execute it from each page.

Look at the following simple example.

check.php Code

<?php
    @session_start();
     
    // ACCOUNT and PASS
    $ok_account = "admin";
    $ok_pass = "kanri";
     
    // Login check
    $flg = false;
    $account = $_SESSION['account'];
    $pass = $_SESSION['pass'];
    if ($account == $ok_account and
            $pass == $ok_pass){
        $flg = true;
    }
    // Processing when not logged in
    if (!$flg){
        echo "<html><body><h1>NOT LOGIN!!!</h1>";
        echo '<a href="./index.php">back to login page.</a>';
        echo "</body></html>";
        exit;
    }
?>

Example Page Using check.php

<?php include_once('./check.php'); ?>
<!DOCTYPE html>
<html lang="ko">
    <head> 
        <meta http-equiv="Content-Type"  content="text/html; charset=UTF-8" /> 
        <title>sample page</title>
    </head>
    <body>
        <h1>Index2.php!</h1>
        <p>[Account: <?php echo htmlspecialchars($account); ?>]</p>
        <p>This is a newly prepared page.</p>
        <hr>
    </body>
</html>

Here, create a file called check.php in the same location as index.php, and prepare the login check processing there. Then, at the beginning of any page that requires login checking, such as index2.php, write the following single line.

<?php include_once('./check.php'); ?>

With only this, the page cannot be viewed unless the user is logged in. Here, the function include_once is used. It loads the script file specified as its argument only once. When check.php is imported, the script is executed at that point, so if the user is not logged in, an error is displayed and exit is executed. Naturally, the content after include_once on that page will not be displayed.

 

You now roughly understand the basics of a login system. After this, if you devise a more solid structure for managing accounts and passwords, you should be able to create a reasonably usable login system.