Skip to content

Instantly share code, notes, and snippets.

@camilleriluke
Created December 3, 2014 17:32
Show Gist options
  • Save camilleriluke/e9855af3bc5e044a5ebf to your computer and use it in GitHub Desktop.
Save camilleriluke/e9855af3bc5e044a5ebf to your computer and use it in GitHub Desktop.
Simple Session Example Test
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Session example test</title>
</head>
<body>
<h1>Session exmaple test</h1>
<form action="session-example.php" method="post">
<label for="fullname">Full Name: </label><input type="text" name="fullname">
<input type="submit" value="Create Session">
</form>
</body>
</html>
<?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Session example test</title>
</head>
<body>
<h1>Session exmaple test</h1>
<?php
// In case we want to remove the session
if (isset($_POST['destroySession'])) {
// Ask PHP to destory the session
session_destroy();
// Explicitly reset all the session variables
$_SESSION = array();
}
// Is this a POST request?
if (isset($_POST['fullname'])) {
// We have a new user visiting
// Set the visit counter to 1 (first time visiting)
$_SESSION['visitCounter'] = 1;
// Set the name of who is visiting on the session
$_SESSION['name'] = $_POST['fullname'];
echo "<p>You just send a new POST request!</p>";
}
// Check if we ever had a session
if (isset($_SESSION['visitCounter']) && isset($_SESSION['name'])) {
// Get the visit counter from the session
$visitCounter = $_SESSION['visitCounter'];
// Get the full name from the session
$fullName = $_SESSION['name'];
// Increment the visit counter
$_SESSION['visitCounter'] = $visitCounter + 1;
echo "<p>Hello <b>$fullName</b>. Visit count: <b>$visitCounter</b>.</p>";
echo "<a href='./session-example.php'>Refresh page</a></p>";
// Close the PHP tag, so we can the session destroy form in HTML
?>
<form action="./session-example.php" method="post">
<input type="hidden" name="destroySession">
<input type="submit" value="Destroy Session">
</form>
<?php
// Open PHP tag again so we can handle the else case
// where no variables are found in the session.
} else {
echo "You never visited the <a href='./landing.html'>landing page</a>.";
}
?>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment