Isaac's Session Demonstration
- Submit will add to a SESSION array.
- Refresh will reload the page and display your active session history.
- Clear Session will empty the SESSION array.
Session History Array Contents:
No history in session yet.
No history in session yet.
<?php
// 1. Start the session first before any output
session_start();
error_reporting(E_ALL); // set error reporting to all
$self = basename($_SERVER['SCRIPT_NAME']);
$first_variable = '';
$second_variable = '';
// Initialize the session array if it doesn't exist yet
if (!isset($_SESSION['session_history'])) {
$_SESSION['session_history'] = array();
}
$submit = isset($_POST['submit']) ? $_POST['submit'] : null;
switch ($submit) {
case 'Submit':
$first_variable = isset($_POST['first_variable']) ? $_POST['first_variable'] : null;
$second_variable = isset($_POST['second_variable']) ? $_POST['second_variable'] : null;
if ($first_variable !== '' && $second_variable !== '' && $first_variable !== null && $second_variable !== null) {
$full_variable = $first_variable . ' ' . $second_variable;
// Add the new value into our Session history array
$_SESSION['session_history'][] = $full_variable;
}
break;
case 'Refresh':
break;
case 'Clear Session':
// Clear the session history array
$_SESSION['session_history'] = array();
// Clear inputs
$first_variable = '';
$second_variable = '';
break;
}
include('includes/header.php');
?>
<h1>Isaac's Session Demonstration</h1>
<ul class="circle">
<li>Submit will add to a SESSION array.</li>
<li>Refresh will reload the page and display your active session history.</li>
<li>Clear Session will empty the SESSION array.</li>
</ul>
<h3>Session History Array Contents:</h3>
<?php if (!empty($_SESSION['session_history'])): ?>
<ul>
<?php foreach ($_SESSION['session_history'] as $past_value): ?>
<li><?php echo htmlspecialchars($past_value); ?></li>
<?php endforeach; ?>
</ul>
<?php else: ?>
<p><em>No history in session yet.</em></p>
<?php endif; ?>
<hr>
<form name="my_form" action="<?php echo htmlspecialchars($self); ?>" method="post">
<fieldset>
<legend>Session Variables</legend>
<p>
<label for="first_variable">First Variable:</label>
<input type="text" size="36" id="first_variable" name="first_variable" value="<?php echo htmlspecialchars($first_variable); ?>">
</p>
<p>
<label for="second_variable">Second Variable:</label>
<input type="text" size="36" id="second_variable" name="second_variable" value="<?php echo htmlspecialchars($second_variable); ?>">
</p>
</fieldset>
<br>
<input type="submit" name="submit" value="Submit">
<input type="submit" name="submit" value="Refresh">
<input type="submit" name="submit" value="Clear Session">
</form>
<br>
<?php include('includes/footer.php'); ?>