How To implement sessions in PHP

Starting a Session

To begin a session in php there are two ways you can do this.the first and simplest is to begin a script with a call to the session_start() function

session_start();

The function checks to see whether there is already a current session.if not, it will essentially create one ,providing access to the global $_SESSION array.if a session already exist,session_start(); loads the registered variables so that the user can use them.It is essential to call session_start() at the start of all your scripts that use sessions.if this function is not called ,anything stored in the session will not be available to this script.
the second way you can begin a session is to set PHP to start one automatically when someone comes to your site.you can do this by using session.auto_start option in your php.ini file.the advantage is that with auto_start enabled,you cannot use objects as session variables,this is because the class definition for that object must be loaded before starting the session to create the object in the session.


Registering Session Variables in PHP

To create a session variable,you simply set an element in this array as follows:

$_SESSION[‘myvar’]=5;

The session variable above will be tracked until the session ends or it is manually unset.the session may naturally expire because of  the session.gc_maxlifetime setting in the php.ini file.this settings determines the amount of time (in seconds) that a session will last before it is ended by the garbage collector.

Using Variables

To bring session into scope for use you must first start a session calling session_start() You can then access the variable via the $_SESSION array.

$_SESSION[‘myvar’].

When using an object as a session variable,it is important to include the class definition before calling the session_start() to reload the session variables hence PHP will know how to reconstruct the session object.
Remember that variables can be set by the user via GET or POST.you can check a variable to see whether it is a registered session by checking in $_SESSION.

If (isset($_SESSION[‘myvar’])) …..

Unsetting existing Variables and Destroying the session

When you are done with a session variables we can unset it.these can be done in two ways.

Unset($_SESSION[‘myvar’]);

Do not unset the whole $_SESSION array because doing so will effectively disable sessions.in unset of  all session variables at once use.

$_SESSION=array();

When you are done with a session,you should first clear all the variables and then call

Session_destroy(); //it cleans up the session ID
php code

Total
0
Shares
Leave a Reply

Your email address will not be published.

Previous Post
linux

How to Calculate Dates in PHP

Next Post

Concepts on Kali Linux Penetration Testing

Related Posts