|
You cannot track variables across a user session unless you start the session on each page on which you want to use or alter those variables. Starting a session uses the session_start() function:
session_start();
session_start() takes no arguments. If you are starting a new session, then the function initializes the session and creates the necessary temp files to track the session. If a $PHPSESSID is found by the function, either by a cookie or a GET variable, then the function resumes the current session and the page has access to any variables that have been registered to the session.
Once you have started the session, you need to register some variables with it. The session will not track variables until they have been registered using the session_register() function:
session_register(STRING);
The STRING argument to session_register() should be the name of the variable that you want to register with the session so that it may be accessed across any session-enabled pages.
Once you have started the session and registered one or more variables, you can use those variables across any session enabled pages on your site.
Example:
<?php
session_start();
if(isset($_SESSION['views'])) {
$_SESSION['views'] = $_SESSION['views']+ 1;
} else {
$_SESSION['views'] = 1;
}
echo "views = ". $_SESSION['views'];
?>
Destroying Sessions:
There are two ways to combat the buildup of files in your temporary directory that will not, in most cases, adversely affect your users' sessions.
unset() function is used to destroy a session variable. Here is the example.
<?php
session_start();
if(isset($_SESSION['cart']))
unset($_SESSION['cart']);
?>
session_destroy();
session_destroy() takes no arguments. session_destroy() unregisters all session variables associated with the user session and removes any session files created by the session. Remember that even if a variable is unregistered with a session, the variable still exists with its value intact on the current page.
|