HTTP is a stateless protocol. So, how can we retain state (persistence)? We will use sessions.
HTTP/PHP session information transfer model:
http://phoenix.goucher.edu/process.php?name=tom
Accessed through _GET
associative array in PHP:
$name = $_GET["name"]; example: Session ID (SID) passed as GET parameter:
echo "<A href=\"http://phoenix.goucher.edu/process.php?" . SID . "\">";
stdin
. _POST
associative array.
_SESSION
associative array.Sessions exist until browser is closed or PHP garbage collector removes the session data file.
Establishing a session and writing session variables:
session_start(); $_SESSION["username"] = $username; $_SESSION["password"] = $password;
Checking to see if a session variable already exists:
if (isset($_SESSION["username"]) $username = $_SESSION["username"]; else $_SESSION["username"] = $username;
Deleting a session variable (enhanced security):
unset($_SESSION["username"]);
Also possible to delete entire session --- see online docs.
This demonstrates a simple script which counts how many times the user has accessed pages on a website. It maintains four session variables (on for each page on the site). Note that the SID and the current selected page (whichPage) are passed as GET parameter.