Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I use sessions in PHP 4.1.0+?

Coding

How do I use sessions in PHP 4.1.0+?

by  sonnysavage  Posted    (Edited  )
To start a session:
Code:
session_start();
NOTE:
Code:
session_start()
must be executed before any data is sent to the browser because it sends header information.


To set data into a session:
Code:
$_SESSION['value_identifier'] = "value";

Code:
$_SESSION
is used just like any other PHP array with a couple of exceptions. When you call
Code:
session_start()
in subsequent pages, the values you've set get restored. Secondly, and very conveniently, it is an "superglobal". This means that you don't have to do anything special to access it's values in functions or classes.

Example:
Code:
<?php
session_start();
$_SESSION['message'] = "Hello world!<br />\n";

function Message() {
  return "Function: "$_SESSION['message'];
}

class Message {
  function Get() {
    return "Object: ".$_SESSION['message'];
  }
}

echo $_SESSION['message'];
echo Message();
$Message = new Message();
echo $Message->Get();
?>

To destroy a session:
Code:
<?php
// Initialize the session.
session_start();
// Unset all of the session variables.
$_SESSION = array();
// Finally, destroy the session.
session_destroy();
?>

PHP Manual Links:
Sessions:
http://www.php.net/manual/en/ref.session.php
PHP Predefined Variables (MORE autoglobals!):
http://www.php.net/manual/en/reserved.variables.php
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top