PHP Tutorials

Session Variables in PHP

Using Session Variables in PHP

Using Session Variables in PHP

In this Tutorial you'll learn about Sessions Variables, Setting and Destroying them using PHP. This includes:

  • What is a Session Variable?
  • Why do we need a Session variable?
  • How to set and destroy a Session Variable

What is a Session Variable?

Session variables are similar to cookies, that is they are used to store information for a particular period of time. The values in session variables exist only till the session exists. They are used to carry information from one page to another of a web site. 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 any number of times until the session is ended.

Why do we need a Session Variable?

In web sites, passing information between pages using a query string is very difficult. For example once you log into a site, passing the username to all the pages of the site using query string is very difficult, but this can be done 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:

Syntax:

session_register("string"); // string - mention the name of the session variable

Example: session_register("UserName");

UserName - name of the session variable

Destroy a Session Variable

They can be destroyed using 'session_destroy' function. This is used to end a session when the user logs out. The code for destroying all the session variables stored in the server is given below:

Syntax:

session_destroy();

Example: session_destroy();

Destroy a Session variable

In the above code it will destroy/delete all the session variables that are stored in the server. In some cases we may want to delete only a particular session variable, this can be done by specifying its name as shown below:

Syntax:

session_unregister("string"); //string - name of the session variable

Example: session_unregister("UserName");

UserName - name of the session variable

That's it you've learnt how to use Session variables in PHP.

Please like, +1, link to and share this SmartWebby resource if you found it helpful. Thanks!