📚 PHP Tutorial

PHP Tutorial

Learn PHP concepts with simple explanations, examples and practical notes.

Handling Sessions in PHP

A session is a small piece of information which is stored at server side.And session is used to store and pass information from one page to another temporarily(until user close the website).

A session technique is widely used in shopping websites where we need to store and pass cart information e.g.user name, product code, product name, product price etc from one page to another.

In simple words, A session is a way to store information (in variables) to be used across multiple pages.

Start a PHP session :

☞ session_start() function is used to start the session.It starts a new or resumes existing session.

Example:
session_start();

 Note : The session-start() function must be the very first thing in your document.

To get and set session variables :

☞ $_SESSION is an associative array that contains all session variables.And it is used to set and get session variable values.


Example: To set session variable or store information in session variable

$_SESSION["name"] = "StudyGlance";

Example: To get session variable or get information from session variable

echo $_SESSION["name"];


Example1:

A simple example to understand working with sessions in PHP. In this, there are two PHP programs, first program (FirstPage.php) is to create session variables and store information. And the second program (SecondPage.php) is to get the information from the session variable.

Example: "FirstPage.php"



Example: "SecondPage.php"


Output :

image
After clicking on the above Hyperlink

image

Example2:

In this example, reading input from a text field and storing it in a session variable after which another page reads the value of the session variable.

Example: "sessionPage1.php"



Example: "sessionPage2.php"


Output :

image
Once the SUBMIT button has been pressed

image

Destroying Session :

☞ session_destroy() function is used to destroy all session variables completely.


Example:

session_destroy();

 Note : Unlike a cookie, the information is not stored on the users computer.