Session Management using php
In Php Let us learn about session variables in Php:
- What is a Session Variable?
- Why do we need a Session variable?
- How to Use Session Variable ?
What is a Session Variable?
Session variables are used to store information for a particular period of time at server side if browser is not closed forcefully. The values in session variables exist only till the session exists. They are used to carry information from one page to another page . We can create a session using a session identifier and store it in the server. When the client makes any request, the data stored in the session variable can be accessed by PHP.
Why do we need a Session Variable?
In web sites, passing information between pages using a query string is insecure . For example once you log into a site, passing the username to all the pages of the site using query string is very difficult and insecure , but handled easily using Session variables. These variables can be used to pass information from one page to another without using a query string, since it is easy to maintain and retrieve.
How to set Session Variables
Session variables can set using ‘session_register’ function in PHP as shown below:
Example: session_register(“loginName”); // where loginName is the name of session variable.
Destroy a Session Variable
Session variable’s can be destroyed using function “session_destroy” as it happens most of time when user logs out. The code for destroying all the session variables stored in the server is given below:
Example : session_destroy();
Above case will destroy all the session variables stored at server but in some cases we may want to delete only a particular session variable, that can be done by following syntax .
Example: session_unregister(“loginName”); // where loginName is the name of session variable.
Session Variable Existence:
To check wither variable exists in session or not we can use following code :
Syntax : session_is_registered(“VarialbeName”);
Example : !session_is_registered(“loginName”); // where loginName is the name of session variable.
Setting Value to Session Variable :
Syntax : $_SESSIOIN[“variableName”]=”my Value”;
Example : $_SESSIOIN[“loginName”]=”Khalid Rauf”; // where loginName is session variable;
Getting Value of Session Variable :
Syntax : $GetVariable = $_SESSIOIN[“variableName”];
Example : $logid = $_SESSIOIN[“loginName”]; // where loginName is session variable;