PHP Sessions

Hey Guys,
In this PHP tutorial, you are going to learn about creating and using sessions in PHP.

Sessions are one of the ways to create common data which can be used on any page of the project. Once the session variables are set we can use them across any page of the same project file.

What Is a Session in PHP:

When we work with a certain application the web server does not know who you are, this problem can be solved by using sessions.

Sessions store the user data and this information can be shared between all the pages of an application.

Once the session variables are set we can access them across all the pages till they are unset.

We can access and modify them easily.

Starting the Session:

A Session is started using session_start( ) function.

After creating a session we can create session variables using $_SESSION[“variable_name”] = value .

Once after assigning values to the session variables we can access them across the application.

Here we use session_write_close( ) function to close session.

<?php

session_start();

//assigning session_variable values 

$_SESSION["a"] = "hii";

session_write_close();

?>

Accessing and Modifying of the Session Variables:

Once the session variables are set we can access them in any file of the same program by simply starting the session in the particular file.

By using $_SESSION[ ] we can modify the values of the session.

<?php session_start();

 //accessing the session_variables 

echo $_SESSION["a"];


 //modifying the session_variables

$_SESSION["a"] = "hello";

 echo $_SESSION["a"];

 ?>

 

Destroying a Session:

A session and its variables are destroyed by using the session_destroy( ) function.

This function destroys the present session and the variables which are declared in the session.

//destroys the session and its variables

sesson_destroy()

We can destroy the variables with out destroying the session using session_unset( ) function

This function removes all the session variables with out destroying the session.

// removing all the variables of a session
   session_unset();

You can also check PHP program to check whether a given number is prime or not by clicking here.

Also, read:

 

Leave a Reply

Your email address will not be published. Required fields are marked *