PHP 5 Sessions
PHP session is used to store information on the server. The data will be available to all pages in one application.
A session creates a file in a temporary directory on the server where registered session variables and their values are stored.
Starting a PHP Session
Before use session variables, you must first start the session using the session_start() function.
The Function session_start() should be in starting and you can't send anything to the browser before it.Example:
<?php session_start(); ?> <html> <body> </body> </html>
When you start a session a unique session id (PHPSESSID) for each visitor/user is created. You can access the session id using the PHP session_id() function or predefined constant PHPSESSID.
Storing a Session Variable
Associative array called $_SESSION is used to store information is a session. These variables can be accessed during lifetime of a session.Example:
<?php session_start(); // store session data $_SESSION["username"] = "nikita"; $_SESSION["email"] = "firstname.lastname@example.org"; //retrieve session data echo $_SESSION["username"]; echo "<br>"; echo $_SESSION["email"]; ?>
Destroying a Session
A complete PHP session can be destroyed by using session_destroy() function, which does not require any arguments.Example:
<?php session_start(); session_destroy(); ?>
If you wish to delete a single session variable then you can use unset() function.Example:
<?php session_start(); if(isset($_SESSION[username])) unset($_SESSION[username]); ?>
|« Previous Chapter |
|Next Chapter » |