Saving Arrays in a Session

You can collect the data to be stored in an array and save them with a session. The $_SESSION array accepts simple scalar variables, but can also acept arrays.

This is the script to do the selection.

<?php
// Enable output buffering. No output is sent from the script
// (other than headers). It is saved in an internal buffer
ob_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN">
<head>
<title>Saving Arrays in a Session</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<p>
<?php

if (isset($_POST['submit'])) {
		process_form();
	}
	else {
		display_form();// display form for the first time
	}

function display_form() {
	echo <<<HTML
	<h2>Movie categories</h2>
	<form action = "$_SERVER[SCRIPT_NAME]" method="post">
	<select name="movies[]" multiple=multiple size="7">
		<option value="Action">Action</option>
		<option value="Comedy">Comedy</option>
		<option value="Drama">Drama</option>
		<option value="Horror">Horror</option>
		<option value="Family">Family</option>
		<option value="Foreign">Foreign</option>
		<option value="Fantasy">Fantasy</option>
	</select>
	<br />
	<input type="submit" name="submit" value="Select category" />
	</form>
HTML;
}

function process_form() {

	// Start session
	session_start();
	if ( !isset($_SESSION['choices'])) {
		// create an array
		$_SESSION['choices']=array();
	}
	if ( is_array($_POST['movies'])) {
		// Join the values
		$items = array_merge($_SESSION['choices'], $_POST['movies']);
		$_SESSION['choices'] = array_unique($items);
		// redirect to the movies page
		header('Location: movies.php');
	}
	else {
		echo "<p>You did not select any movie categories.</p>";
		display_form();
	}
}
?>
</p>
</body>
</html>
<?php
// Flush the buffer and end output buffering.
ob_end_flush();
?>

View the effect

This is the script to display the selection.

<?php
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN">
<head>
<title>Movie Categories</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<p>
<?php

if (is_array($_SESSION['choices'])) {
	foreach ($_SESSION['choices'] as $movie) {
		echo $movie, "<br />";
	}
}
else {
	echo "<p>You have not selected any movie categories yet</p>";
}

echo "<p><a href=\"example_d.php\">Log out</a></p>";
echo "<p><a href=\"example_ar.php\">Select the movie categories</a></p>";

?>
</p>
</body>
</html>

View the effect


Sessions in PHP | Introduction | Basic Session Functionality | Creating a Session | Accessing Session Variables | Deleting a Session | Implementing a Login System with Sessions | Saving Arrays in a Session | Using Cookies with Session | Sessions without Cookies | Potential Session Problems
© 2008: Hann So
email: hso@voyager.deanza.edu