Core PHP

Start Session and Set Variables

This PHP example program demonstrates how to start a session and set session variables. The first page, StartSessionAndSetVariables.php begins the session and sets two session variables: $_SESSION[Something1] and $_SESSION[Something2]. These variables are set to the values Some Value 1 and Some Value 2 after the session is set up.

With the session variables set, we can go to a new page via a link, like NextPage.php and access the values in these variables, as long as we remember to start the session again at the beginning of the file.

The listing below show the PHP for two separate pages with a link between them and the output that was generated when we visited them.

StartSessionAndSetVariables.php

<?php
	session_start();
?>
<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <h1>Start Session</h1>
<?php
	echo "You have been given a session ID:<br />\n";
	echo "Session ID: ".session_id()."<br/><br />\n";
	// Set some session values that we wish to preserve.
	$_SESSION["Something1"] = "Some Value 1\n";
	$_SESSION["Something2"] = "Some Value 2\n";
	echo "Stored Session Values:<br />\n";
	// Write out all of the session variables and their values
	foreach ($_SESSION as $sKey => $sValue) {
		echo "&dollar;_SESSION[".$sKey."] = ".$sValue."<br />\n";
	}
	echo "<br />\n";
?>
  </body>
  <a href="NextPage.php">Next Page</a>
</html>
 
 

StartSessionAndSetVariables.php Output

 

NextPage.php

<?php
	session_start();
?>
<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <h1>Another Session Page</h1>
<?php
	echo "You still have a session ID:<br />\n";
	echo "Session ID: ".session_id()."<br/><br />\n";
	echo "Stored Session Values:<br />\n";
	// Verify that the session values are still set on the next page.
	// Write out all of the session variables and their values
	foreach ($_SESSION as $sKey => $sValue) {
		echo "&dollar;_SESSION[".$sKey."] = ".$sValue."<br />\n";
	}
	echo "<br />\n";
?>
  </body>
</html>
 
 

NextPage.php Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.