The power of using sessions resides on the ability to pass information regarding to the user from one page to another. When using sessions your site users get assigned a unique id that can be in the form of a cookie or a query string. To start a new session you have to use the session_start() function. This function is required on every page where you want to make use of session variables. To use sessions in the way we are going to show here the user must have cookies enabled on his/her browser.
The function session_register() registers a variable for the current session. After registering a variable it will be available on all your site pages (site pages that include session_start()). Lets see an example. First save the following code as a php file:
|
<?php
session_start();
session_register( "username" );
session_register( "password" );
$username="terry";
$password="moves";
echo "Username set";
?> |
Then save the below code as another php file:
| <?php
session_start();
?>
<html>
<body>
<?php
echo "Your username is: $username <br>";
echo "Your password is: $password ";
?>
</body>
</html> |
Now visit the first page and then the second one. When you visit the second one you will get
Your username is: terry
Your password is: moves
In the second code session_start() gives us access to all of the session variables without having to declare them on the page that we plan to use them.
Ending a session
If you want to unregister a variable you can make use of the session_unregister function.
For example, this line of code will unregister the username variable:
session_unregister(username)
If instead of that you want to end the session as a whole you can use the session_destroy() function. Calling this function however would not destroy session variables immediately but on the next time you call the page. To destroy session variables you need to use the session_unset() function. Lets see an example, place this code on yet another page and load it
|
<?php
session_start();
session_destroy(); // session ends here
print $password; // the password is printed
session_unset(); // this will destroy the variable
print $password; // the variable is finally destroyed
?> |