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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

PHP 4.1.0+ Sessions

Status
Not open for further replies.

sonnysavage

Programmer
May 29, 2002
130
US
I've seen a LOT of session-related questions lately, so I thought I'd write this little tip.

To start a session:
Code:
session_start();

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

$_SESSION is used just like any other PHP variable with a few exceptions. When you call session_start() in subsequent pages, the values you've set get restored. Secondly, and very conveniently, it is an "autoglobal". 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[&quot;message&quot;] = &quot;Hello world!&quot;;

function Message() {
     return &quot;Function: &quot;.$_SESSION[&quot;message&quot;].&quot;<br />&quot;;
}

class Message {
     function Get() {
          return &quot;Object: &quot;.$_SESSION[&quot;message&quot;].&quot;<br />&quot;;
     }
}

echo $_SESSION[&quot;message&quot;].&quot;<br />&quot;;
echo Message();
$Message = new Message();
echo $Message->Get();
?>

Feel free to add corrections and/or errata. Enjoy!
 
Dude, write a FAQ ______________________________________________________________________
Perfection in engineering does not happen when there is nothing more to add.
Rather it happens when there is nothing more to take away.
 
Um, ok... I thought I was writing a faq... Sorry, I'm pretty new to this site.
 
It's now in a FAQ!
Here:
faq434-2036
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top