Session in PHP
Session in PHP
In PHP, Session is used to store the information temporarily for a particular session time. The usage of this session are shown below.
Starting a PHP Session
It is a first step in using a session, before storing anything is session, you must start the session. The syantax is
session_start();
It start up your PHP session. It must be at the very beginning of your code, before any HTML content.
Now the session is started, We can set any number of variables and values in the particular session, by assigning in the associative array $_SESSION, It Syntax is
$_SESSION[’variable’] = value;
Example:
$_SESSION[’username’]=’aaa’;
$_SESSION[’password’] = ‘pass’;
here, We can retrieve these values in any of the page in this session. by using
echo $_SESSION[’username’]; // It displays aaa
We can also retrieve this by using print_r by print_r($_SESSION);
It displays
Array
(
[username] => aaa
[password] => pass
)
Session Name
We also set the name for the particular session by using session_name, Its syntax is
string session_name ( [string name])
By using this function, we can both set and get the name of the session.
session_name() returns the name of the current session. If name is specified, the name of the current session is changed to its value.
Example :
To Set the name of the Session
session_name(”newsession”);
To get the Session name
$sesname = session_name();
It returns the name of the current session.
Session ID
Similarly We also set and get the Id for the Particular session. Its Syntax is
string session_id ( [string id])
session_id() returns the session id for the current session. If id is specified, it will replace the current session id.
Session Destroy
After Using the Session, we destroy it, for safe. It Syntax is
bool session_destroy ( void)
It destroy the all data registered in the session.
session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie.
This function returns TRUE on success and FALSE on failure to destroy the session data.
Sample Code
<?php
session_start();
$_SESSION[’eno’] = 101;
$id = session_id();
session_name(”test”);
print_r($_SESSION);
session_destroy();
?>
