×
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!
  • Students Click Here

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Jobs

Coding

How do I use sessions in PHP 4.1.0+? by sonnysavage
Posted: 14 Jun 02 (Edited 27 Feb 04)

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

Back to PHP FAQ Index
Back to PHP Forum

My Archive

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close