Server-Side Scripting/Cookies and Sessions/PHP

index.php edit

<?php

// Demonstrates session and cookie processing. The username is stored
// as a cookie and an internal userid is saved in a session variable.
// Also demonstrates secure password authentication using bcrypt salt
// and hash.
//
// References:
//  https://en.wikibooks.org/wiki/PHP_Programming
//  https://www.w3schools.com/php/php_cookies.asp
//  https://www.w3schools.com/php/php_sessions.asp
//  https://www.php.net/manual/en/function.password-hash.php

$users = [
    // Password is the same as the username, just salted and hashed.
    // Don't do this in a production application! Use custom passwords.
    array("userid"=>1, "username"=>"admin", 
        "password"=>"$2y$10$.XSuDyI8NcYWCt6e638Or.s1M7.KCdr5K6qfMI8PQdBigepXI2lvG"),
    array("userid"=>2, "username"=>"test", 
        "password"=>"$2y$10$Z46BBxS25DGCpQACucaqVuPxZx9.j18Shzvb95Vz5C3Ot9ES3Jwiy")
];

main();

function main() {
    global $username;
    global $userid;
    global $cookie;
    global $session;
    global $welcome;

    session_start();
    switch($_SERVER["REQUEST_METHOD"]) {
        case "GET":
            $username = get_username();
            $userid = get_userid();
            break;
        case "POST":
            if (isset($_POST["reload"])) {
                $username = get_username();
                $userid = get_userid();
            } elseif (isset($_POST["log-out"])) {
                $username = get_username();
                $userid = "";
                $_SESSION["userid"] = $userid;
            } elseif (isset($_POST["forget-me"])) {
                $username = "";
                $password = "";
                setcookie("username", $username);
                $_SESSION["userid"] = $userid;
            } else {
                $username = $_POST["username"];
                $password = $_POST["password"];
                $userid = authenticate_user($username, $password);
                if ($userid != "") {
                    setcookie("username", $username);
                    $_SESSION["userid"] = $userid;
                } else {
                    $username = get_username();
                    $userid = get_userid();
                }
            }
            break;
        default:
            echo "Unexpected request method:" . $_SERVER["REQUEST_METHOD"];
            break;
    }

    $cookie = get_cookie($username);
    $session = get_session($userid);
    $welcome = get_welcome($username, $userid);
}

function get_username() {
    if (isset($_COOKIE["username"])) {
        return $_COOKIE["username"];
    } else {
        return "";
    }
}

function get_userid() {
    if (isset($_SESSION["userid"])) {
        return $_SESSION["userid"];
    } else {
        return "";
    }
}

function get_cookie($username) {
    if ($username == "") {
        return "FALSE";
    } else {
        return "TRUE";
    }
}

function get_session($userid) {
    if ($userid == "") {
        return "FALSE";
    } else {
        return "TRUE";
    }
}

function get_welcome($username, $userid) {
    if ($username != "" && $userid != "") {
        return "Welcome back " . $username . "! You are logged in.";
    }
    else if ($username != "") {
        return "Welcome back " . $username . "! Please log in.";
    }
    else {
        return "Welcome! Please log in.";
    }
}

function authenticate_user($username, $password) {
    foreach($GLOBALS["users"] as $user) {
        if ($user["username"] == $username) {
            if (password_verify($password, $user["password"])) {
                // Should track successful logins
                return $user["userid"];
            } else {
                // Should track failed attempts, lock account, etc.
                return "";
            }
        }
    }
}

function generate_hashed_password($password) {
    // Use this function to generate hashed passwords to save in 
    // the users list or a database.
    $hashed = password_hash($password, PASSWORD_BCRYPT);
    return $hashed;
}

?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Lesson 12</title>
    <link rel="stylesheet" href="styles.css">
</head>

<body>
    <h1>Cookies and Sessions</h1>
    <p>Cookie: <?=$cookie?><br>Session: <?=$session?></p>
    <p><?=$welcome?></p>
    <hr>
    <form method="POST">
        <p><label for="username">Username:</label>
            <input type="text" id="username" name="username" value="<?=$username?>">
        </p>
        <p><label for="password">Password:</label>
            <input type="password" id="password" name="password">
        </p>
        <input type="submit" id="log-in" name="log-in" value="Log In">&nbsp;
        <input type="submit" id="log-out" name="log-out" value="Log Out">&nbsp;
        <input type="submit" id="forget-me" name="forget-me" value="Forget Me">&nbsp;
        <input type="submit" id="reload" name="reload" value="Reload">
    </form>
</body>

</html>

Try It edit

  1. Use Docker/PHP and copy and paste the code above to run as the PHP application.