This example shows how to register a session variable, use it in a separate page, and close a session.
Sessions are a way of making the web server store variables while a particular user is on a site. Instead of using cookies to send all data with each request, using a session allows you to set only one cookie and have the server store the data.
You can start a session using session_start(). You can then register variables using session_register(). To unregister a variable use session_unregister(). To close a session, use session_destroy().
To register a variable named $count, I could do this:
session_start() ;
if (!session_is_registered("count"))
{
session_register("count") ;
$count = 0 ;
}
If there is no session started, this will begin a new session and register $count. If a session is already started, but $count is not registered, it will create the new variable. On the next page that needs to use the session, begin the file with:
session_start() ;
After this point, the session variables can be accessed. When a session is no longer needed, try to direct the user to a logout page where the session can be killed. Otherwise the session will hang around until the server eventually kills it. In the meantime, it is possible for someone to hijack the session. To kill a session, use session_destroy():
if ( isset($PHPSESSID))
{
$message = "Session ended" ;
session_start() ;
session_destroy() ;
}
else
{
$message = "No session" ;
}
While you cannot guarantee that the user will close a session, it is best to give them the option.
You can see how a session works by playing with the examples: