<?php
    // NEED this if you want to use $_SESSION superglobal
    //     associative array! (BEFORE anything is output
    //     to the browser)

    session_start();
?>

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">

<!--
    Our first session example

    Adapted from an old example that was originally at
    http://www.php.net/manual/en/re.session.php
    (but no longer exists when I checked in Spring 2025)

    by: Sharon Tuttle
    last modified: 2025-04-22

    you can run this using the URL:

https://nrs-projects.humboldt.edu/~st10/s25cs328/328lect13-1/try-session-1.php
-->

<head>
    <title> Sessions, take 1 </title>
    <meta charset="utf-8" />

    <link href="https://nrs-projects.humboldt.edu/~st10/styles/normalize.css"
          type="text/css" rel="stylesheet" />

</head>

<body>
    <h1> Playing with PHP sessions </h1>

    <?php
    // if I am getting for the first time, set up a session key "count"

    if (! array_key_exists("count", $_SESSION))
    {
        ?>
        <h2> NOTE: count did NOT exist as a key in $_SESSION! </h2>
        <?php

        // let's add a session key "count"

        $_SESSION["count"] = 0;

        ?>
        <h3> ...but now HAVE added it, with an initial value of:
             <?= $_SESSION["count"] ?> </h3>
        <?php
    }
    else // "count" IS a key in $_SESSION
    {
        ?>
        <h2> NOTE: count DID exist as a key in $_SESSION,
             currently with value: <?= $_SESSION["count"] ?> </h2>

        <?php
        $_SESSION["count"]++;

        ?>
        <h3> ..but now incremented that value, so it is now:
             <?= $_SESSION["count"] ?> </h3>
        <?php
    }
    ?>

    <p> AFTER that initial part, count session key now has the value:
        <?= $_SESSION["count"] ?> </p>

    <?php
    // I decide that if when/if the count exceeds 5, I will destroy the
    //    current session

    if ($_SESSION["count"] > 5)
    {
        ?>
        <p> OH, the count session key's value exceeds 5! Destroying the
            current session! </p>
        <?php
        session_destroy();
    }

    ?>
    <p> <a href="<?= htmlentities($_SERVER["PHP_SELF"], ENT_QUOTES) ?>">
        Try again </a> </p>
   
    <footer>
    <hr />
    <p>
        Validate by pasting .xhtml copy's URL into<br />
        <a href="https://validator.w3.org/nu">
            https://validator.w3.org/nu
        </a>
        or  
        <a href="https://html5.validator.nu/">
            https://html5.validator.nu/
        </a>
    </p>
    </footer>
</body>
</html>