Sessions

Allows the storage/retrieval of data across various site pages, using the $_SESSION super global.

 

Server creates a UID (unique ID) consisting of a long system generated string, to store user information against.

 

UID stored in cookie or sent in URL.

 

Session_start() ;  //required on every page where session processing is used.

 

*note: session_start(); must be before the opening <html> tag, due to HTTP headers (e.g. sessions) being sent before body (HTML code).

 

The required session variables are defined within the super global $_SESSION associative array, as follows:

 

<?php
	session_start() ;

	$_SESSION["myLocation"]  = "London" ;
	$_SESSION["myGuitar"]  = "Yamaha SG2000S" ;
	$_SESSION["myBike"]  = "Ducati" ;

	if(isset($_SESSION[pageViews])) { //check to see if this session variable has been set

		$_SESSION["pageViews"]++ ; //if so increment by one
	} else {
		$_SESSION["pageViews"] = 1 ;//otherwise set to one
	}
?>
<html>
<body>
	<?php echo $_SESSION["myLocation"] . "<br>" ; ?>
	<?php echo $_SESSION["myGuitar"] . "<br>" ; ?>
	<?php echo $_SESSION["myBike"] . "<br>" ; ?>
	<?php echo $_SESSION["pageViews"] . "<br>" ; ?>
</body>
</html>

Displays:

London
Yamaha SG2000S
Ducati
2

 

 

Removing session data is carried out by use of the unset()

 

<?php
	session_start() ;

	if(isset($_SESSION[pageViews])) {

		unset( $_SESSION["pageViews"] ) ;
	}
?>
<html>
<body>
	<?php echo $_SESSION["myLocation"] . "<br>" ; ?>
	<?php echo $_SESSION["myGuitar"] . "<br>" ; ?>
	<?php echo $_SESSION["myBike"] . "<br>" ; ?>
	<?php echo $_SESSION["pageViews"] . "<br>" ; ?>
</body>
</html>

Displays:

London
Yamaha SG2000S
Ducati

 

 

Or completely destroy all session data, using or session_destroy()

 

<?php
	session_start() ;

	$_SESSION = array() ;

	session_destroy();
?>
<html>
<body>
	<?php echo $_SESSION["myLocation"] . "<br>" ; ?>
	<?php echo $_SESSION["myGuitar"] . "<br>" ; ?>
	<?php echo $_SESSION["myBike"] . "<br>" ; ?>
	<?php echo $_SESSION["pageViews"] . "<br>" ; ?>
</body>
</html>

Displays:

 

*note: the above is intentionally blank as the above code destroys all the session data

Leave a Reply