Session in PHP is a way of temporarily storing and making data accessible across all the website pages. It will create a temporary file that stores various session variables and their values. This will be destroyed when you close the website. This file is then available to all the pages of the website to access information about the user.

You need to set the path for this file using the session.save_path setting from the php.ini file. If you don’t set this path, the session might malfunction.

What Is the Use of Session in PHP?

A session in PHP allows the webserver to get the information about when you started a website, what you were doing, when you closed the website and other related information. It is required because, unlike the PC or mobile, the webserver does not have any information about you. That’s where sessions come into the picture.

These sessions have session variables that store all the necessary information into a temporary file. By default, it will destroy this file when you close the website. Thus, to put it simply, a session in PHP helps in storing information about users and makes the data available to all the pages of a website or application until you close it.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

What Happens When You Start a Session in PHP?

The following things occur when a session is started:

  • It creates a random 32 digit hexadecimal value as an identifier for that particular session. The identifier value will look something like 4af5ac6val45rf2d5vre58sd648ce5f7.
  • It sends a cookie named PHPSESSID to the user’s system. As the name gives out, the PHPSESSID cookie will store the unique session id of the session.
  • A temporary file gets created on the server and is stored in the specified directory. It names the file on the hexadecimal id value prefixed with sess_. Thus, the above id example will be held in a file called sess_4af5ac6val45rf2d5vre58sd648ce5f7.

PHP will access the PHPSESSID cookie and get the unique id string to get session variables’ values. It will then look into its directory for the file named with that string.

When you close the browser or the website, it terminates the session after a certain period of a predetermined time.

How to Start a PHP Session?

You can start a session in PHP by using the session_start() function. This function will, by default, first check for an existing session. If a session already exists, it will do nothing, but it will create one if there’s no pre-existing session available.

To set session variables, you can use the global array variable called $_SESSION[]. The server can then access these global variables until it terminates the session. Now that you know what a session is in PHP and how to start one, it’s time to look at an example and see how it works.

Note: It is always recommended to put the session_start() function as the first line in your code, even before any HTML tags.

Example: How to Start a Session in PHP?

In the example below, you will start a session that will count how many times you have visited a website page. For this, you will create a session variable named counter.

<?php

   session_start();

   if( isset( $_SESSION['counter'] ) ) {

      $_SESSION['counter'] += 1;

   }else {

      $_SESSION['counter'] = 1;

   }

   $my_Msg = "This page is visited ".  $_SESSION['counter'];

   $my_Msg .= " time during this session.";

?>

<html>

   <head>

      <title>Starting a PHP session</title>

   </head>

   <body>

      <?php  echo ( $my_Msg ); ?>

   </body>

</html>

Output:

SessioninPHP_1

You can copy-paste this code in a .php file and load it several times to see the number in the counter variable see it in action.

How to Access Values From a Session in PHP?

You can access a session variable’s value by using the global variable $_SESSION. In the example stated below, you will create another session with a variable that stores your name.

<?php  

    session_start();  

?>  

<html>  

<body>  

<?php  

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

    echo "Information set in a variable.<br/>";  

?>

</body>

</html>

Output:

SessioninPHP_2

Now that the variable is set, you will access it from another file. Create another file and write the following code to access the name variable you have just set.

Note: Load both the pages without closing the browser, as it will end the session.

<?php  

    session_start();  

?>  

<html>  

<body>  

<?php  

    echo "User is: ".$_SESSION["name"];  

?>  

</body>  

</html>  

Output:

SessioninPHP_3

How to Destroy a Session in PHP?

Although the web server will terminate the session by default upon closing the browser, you can also destroy it manually. Two functions can help you achieve this.

  • session_destroy(): Calling this function will eliminate all the session variables
  • unset(): Calling this function will kill only the specified session variable

You can also use the session_unset() function to remove all the variables of a session. Let’s look at how to destroy the counter variable that you have created in one of the sessions above.

Example: Using unset() to Destroy a Session Variable

<?php

    unset($_SESSION[‘counter’]);

?>

This will end only the counter variable, but not the others if there are any.

Example: Using session_destroy() to Destroy a Complete Session in PHP

<?php

    session_destroy();

?>

The PHP session_destroy() function does not accept any parameter. Simply calling this function will destroy the entire session in PHP.

How to Turn On an Auto Session?

You don't have to call the start_session() function each time a user visits the website. Instead, you can turn on auto sessions for that. When you turn on the auto session, it will automatically create a session for each visit.

To turn on the auto session, you need to access the php.ini file and set the session.auto_start variable to 1.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

How to Send Sessions Without Cookies?

Do you remember the prompt from websites that says you use cookies, and then there are two options: to accept or deny it. A user can simply restrict the use and storing of cookies in his browser. Without the use of cookies, how will the PHP script find the identifier id of a session? Well, there’s an alternative to that.

You can use constant SID for this purpose. It is defined once the session starts. If the user allows the use of cookies, it will be an empty string. But if the user denies the use of cookies, the constant SID will have a form session_name=session_id. You can use and embed this form unconditionally to register and store variables.

Example: Sending Session ID to the Browser Without Cookies

The following code shows the use of constant SID for sending session IDs to the browser.

<?php

   session_start();

   if (isset($_SESSION['counter'])) {

      $_SESSION['counter'] = 1;

   }else {

      $_SESSION['counter']++;

   }

   $my_Msg = "This page was visited ".  $_SESSION['counter'];

   $my_Msg .= " time during this session.\n";

   echo ( $my_Msg );

?>

<p>

   To continue click here <br />

   <a  href = "newpage.php?<?php echo htmlspecialchars(SID); ?>">

</p>

Output:

SessioninPHP_4

When the user clicks on the link, the constant SID will be sent to the browser along with the session identifier.

Note: The htmlspecialchars(SID) is used in the above code to prevent XSS attacks.

Conclusion

In this article, you have learned everything about a session in PHP. You have also looked at how to send a session ID if the user has not given consent to using cookies in PHP. PHP has become an integral part of full-stack web development. Thus, it is essential to learn PHP if you want to pursue a career in web development. You can opt for Simplilearn’s Full Stack Developer - MERN Stack in collaboration with Caltech CTME  to get hands-on training and online learning materials for excelling in the field of web development. 

Read our next tutorial on PHP isset() Function and enhance your knowledge on PHP functions.

Have any questions for us? Leave them in the comments section of this article. Our experts will get back to you on the same, ASAP!

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 16 Dec, 2024

6 Months$ 8,000
Automation Test Engineer Masters Program

Cohort Starts: 27 Nov, 2024

8 months$ 1,499
Full Stack Java Developer Masters Program

Cohort Starts: 18 Dec, 2024

7 months$ 1,449
Full Stack (MERN Stack) Developer Masters Program

Cohort Starts: 8 Jan, 2025

6 Months$ 1,449