In this PHP tutorial we will see how to start Session in PHP.


A session is a process to store information (in variables) and further to be used this information across multiple pages. Beside in session, the information is not stored on the user’s computer, unlike a cookie.
A session creates a file in a directory on the server for a short period of time where registered session variables and their values are stored. This type of data will be available to all pages on the site during that visit.
And you can find out the location of the temporary directory file is determined by a setting in the php.ini file which is called session.save_path.

What is a PHP Session?

We understood “what is PHP Session?” through an example. Let’s suppose we are working with an application, first we open it, do some task and then close the application. This process is similar like a Session. When we follow these process, computer knows who we are. And it also knows when we start the application and when we close the application.
But when we use internet, there is one issue by storing user information to be used across multiple pages (e.g. usernames, email, etc). By default, session data last until the user closes the browser.



How to Start a PHP Session

A session is simply started with the using of session_start() function. A PHP session variables are hold in associative array which is define by $_SESSION[]. These hold information can be retrieved during lifetime of a session.

<?php
// Start the session
session_start();
?>



Let’s see an example. First we create a page “session-demo.php”. In this new page, we start a new PHP session and define some session variables:

Example#1

<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION["firstname "] = "abc";
$_SESSION["email"] = "test@gmail.com";
echo 'Hi, ' . $_SESSION["firstname"] . ' ' . $_SESSION["email"];?>

</body>
</html>




Destroy a PHP Session

If you want to remove all session data, use session_unset() function for the corresponding key of the $_SESSION associative array, as given in the following example:

Example#

<?php // Starting session session_start();
 // Removing session data 
if(isset($_SESSION["firstname"]))
{ unset($_SESSION["email"]); } ?>



And now to see, to destroy a session completely, simply call the session_destroy() function. When we destroy a session , the session_destroy() function does not need any argument and a single call destroys all the session data.

Example#1

<?php // Starting session 
session_start(); 
// Destroying session 
session_destroy(); ?>

Pin It on Pinterest

Shares
Share This