teaching_web_development

Cookies and Sessions

What are cookies?

Code


<?php
// Note - cannot have any output before setcookie
if (! isset($_COOKIE['var_cookie']) ){
    setcookie('var_cookie', '23', time() + 4000);
}

print_r($_COOKIE);
?>

Sessions

Session code

image

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
    <h1>Login</h1>
    <form action="login.php" method="POST">
        <label for="username">Username:</label><br>
        <input type="text" id="username" name="username"><br><br>

        <label for="password">Password:</label><br>
        <input type="password" id="password" name="password"><br><br>

        <input type="submit" value="Login">
    </form>
</body>
</html>
<?php
session_start();

if (isset($_POST['username'], $_POST['password'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];

    if ($username === 'admin' && $password === 'password12') {
        $_SESSION['login'] = true;
        header('Location: welcome.php');
        exit();
    } else {
        $error = "Invalid username or password.";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
    <h1>Login</h1>

    <?php if (isset($error)): ?>
        <p style="color: red;"><?php echo $error; ?></p>
    <?php endif; ?>

    <form action="login.php" method="POST">
        <label for="username">Username:</label><br>
        <input type="text" id="username" name="username"><br><br>

        <label for="password">Password:</label><br>
        <input type="password" id="password" name="password"><br><br>

        <input type="submit" value="Login">
    </form>
</body>
</html>
<?php
session_start();

if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
    header('Location: login.php');
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Welcome</title>
</head>
<body>
    <h1>Welcome, admin!</h1>
    <p>You are logged in. The session variable <code>$_SESSION['login']</code> is set to <strong>true</strong>.</p>
    <a href="logout.php">Logout</a>
</body>
</html>
<?php
session_start();
session_destroy();
header('Location: login.php');
exit();
?>

(Optional) Session code

<?php
// Note - no output before this
session_start();

if ( !isset($_SESSION['value']) ){
    $_SESSION['value'] = 0;
} else {
    session_destroy();
    session_start();
}
?>

<p>
    < a href = "sessfun.php"> Click me 
    </a>
</p>

<pre>
    <?php
        print_r($_SESSION['value']);
    ?>
</pre>

Sessions without cookies

Video by Dr. Severance