Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What are PHP Sessions?
3.
How to Access Values From a Session in PHP?
4.
Start a PHP Session
5.
Getting Session Variable Values
6.
Modify a PHP Session Variable
7.
Destroying a PHP Session
7.1.
To Destroy a Session 
7.2.
To Destroy Certain Session Data
8.
Sessions without cookies
9.
Security Considerations:
10.
FAQs
10.1.
How long is a PHP session?
10.2.
What is a session handler in PHP?
10.3.
How to give session time in PHP?
10.4.
What is the limit of a PHP session?
11.
Key Takeaways
Last Updated: Sep 7, 2024

PHP Sessions

Author Ranjul Arumadi
2 upvotes

Introduction

When working with an application, we can open it, make changes, and close it. This is similar to a Session. The computer recognizes us. It identifies when we start and stop using the application. However, there is a problem on the internet: the webserver has no idea who we are or what we are doing because the HTTP address does not keep track of the state.

PHP Sessions

This is where PHP sessions come into the picture. PHP session variables address this issue by saving user data that we can use across several pages (e.g., username, favourite colour, etc.). Session variables are persistent until the user closes the browser.

 

As a result, PHP session variables save information about a single user and are accessible from all pages in a single application. Let us look more into what PHP sessions are.

What are PHP Sessions?

PHP session is a means to save data (in the form of variables) on the server rather than the user's machine and reuse it across multiple pages. Unlike a cookie, the information is not saved on the user's computer.

 

On the user's machine, most sessions set a user-key that looks like this: 765487cf34ert8dede5a562e4f3a7e12. The machine is then scanned for a user key when a session is opened on another page. If a match is found, it accesses that session; if not, it creates a new one.

 

A session creates a file in a temporary directory on the server. A setting in the php.ini file can find the location of the temporary file. The file location is called the session.save_path. We must ensure that this path is set before using any session variables.  

 

The following things happen when a session is started −

  • PHP creates a unique identifier for that particular session. The identifier will be a random string of 32 hexadecimal numbers such as 4c9foj34c3pp456hjkop2gy937e5923.
  • PHPSESSID, a cookie, is automatically sent to the user's computer to store the unique session identification string.
  • A file gets automatically created on the server in the designated temporary directory and holds the name of the unique identifier prefixed by sess_,  i.e., sess_4c9foj34c3pp456hjkop2gy937e5923.

How to Access Values From a Session in PHP?

In PHP, you can use the `$_SESSION` superglobal array to access values stored in a session. A session allows you to store data on the server side and retrieve it across multiple page requests. Let's see how you can access values from a session in PHP:

1. Start the session: Before you can access session values, you need to start the session using the `session_start()` function. This function should be called at the beginning of your PHP script, before any output is sent to the browser.

session_start();
You can also try this code with Online PHP Compiler
Run Code

 

2. Store values in the session: To store values in the session, you can assign them to the `$_SESSION` array. You can use any valid PHP variable name as the key.

$_SESSION['username'] = 'JohnDoe';
$_SESSION['age'] = 25;
You can also try this code with Online PHP Compiler
Run Code

 

3. Access values from the session: To access values stored in the session, you can simply use the `$_SESSION` array with the corresponding key.

$username = $_SESSION['username'];
$age = $_SESSION['age'];
echo "Username: " . $username . "<br>";
echo "Age: " . $age;
You can also try this code with Online PHP Compiler
Run Code

In this example, the values stored in the session with the keys 'username' and 'age' are retrieved and assigned to the variables `$username` and `$age`, respectively. You can then use these variables in your PHP code.

 

4. Check if a session value exists: Before accessing a session value, it's a good practice to check if it exists to avoid errors. You can use the `isset()` function to check if a session value is set.

if (isset($_SESSION['username'])) {
   $username = $_SESSION['username'];
   echo "Welcome, " . $username;
} else {
   echo "Username not found in the session.";
}
You can also try this code with Online PHP Compiler
Run Code

 

5. Unset a session value: If you want to remove a specific value from the session, you can use the `unset()` function.

unset($_SESSION['age']);
You can also try this code with Online PHP Compiler
Run Code

This will remove the 'age' value from the session.

 

6. Destroy the session: If you want to completely destroy the session and remove all session data, you can use the `session_destroy()` function.

session_destroy();
You can also try this code with Online PHP Compiler
Run Code

This will terminate the current session and remove all data associated with it.

Remember to always start the session with `session_start()` before accessing or modifying session values. Also, make sure to store sensitive data securely and validate and sanitize user input when working with sessions to prevent security vulnerabilities.

Start a PHP Session

Let's start by making a new page called "new_ session.php." We'll create a new PHP session and set some session variables on this page.

 

We can start a session using the session_start() function.

The PHP global variable $_SESSION is used to set session variables.

 

Keep one thing in mind; the document must begin with the session_start() function. Any HTML tag should come after this.

 

Example:

<?php

// Start the session

session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php

// Set session variables

$_SESSION["Name"] = "Coder";
$_SESSION["favcolor"] = "green";
echo "Session variables are set.";
?>

</body>
</html>
You can also try this code with Online PHP Compiler
Run Code

 

Output:

The $_SESSION[] superglobal array stores session data in key-value pairs. The above example shows that name and favcolor are two session variables storing the data. We can access this stored data throughout the lifetime of a session.

Getting Session Variable Values

Now let’s see how to access the session variable values from our newly created PHP session.

 

We will make a new page called "new_session1.php." We will access the session information we set on the first page ("new_session.php") from this page.

 

Session variables aren't sent to each new page individually; instead, they're retrieved from the session we open at the start of each page (session_start()).

 

It's also worth noting that the global $_SESSION variable stores the values of all session variables, which gives us one more way to show all session variable values.

 

Example:

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Returning session variables that we set on previous page

echo "Name:  " . $_SESSION["name"] . ".<br>";
echo "Favourite colour:  " . $_SESSION["favcolor"] . ".";
?>

</body>
</html>
You can also try this code with Online PHP Compiler
Run Code

 

Output:

One more way to show all the session variables is as follows:

 

Example:

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php

print_r($_SESSION);
?>

</body>
</html>
You can also try this code with Online PHP Compiler
Run Code

 

Output:

Modify a PHP Session Variable

In case you wish to modify a PHP session variable, you can do it by simply overwriting a session variable as shown in the example below:

 

Example:

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php

// To change a session variable, overwrite it
$_SESSION["name"] = "Ninja";
print_r($_SESSION);
?>

</body>
</html>
You can also try this code with Online PHP Compiler
Run Code

 

Output:

Destroying a PHP Session

There are two options to destroy a PHP session. We can either delete the entire session or just a portion of its data. Let's look at a few samples to help us understand it better.

To Destroy a Session 

To destroy a session, use the session_destroy() function. There is no argument required for the session_destroy() function.

 

Example:

<?php

session_start();
session_destroy();

?>
You can also try this code with Online PHP Compiler
Run Code

To Destroy Certain Session Data

To delete only a particular session variable in the $_SESSION associative array, use the unset feature with the corresponding session variable.

 

The argument below removes only the "favcolor" session variable from the associative session array.

 

Example:

<?php
 
session_start();
 
if(isset($_SESSION["name"])){
   unset($_SESSION["favcolor"]);
}
 
?>
You can also try this code with Online PHP Compiler
Run Code

Sessions without cookies

In situations where cookies are disabled, the PHP session will still function. For this to happen, two things have to be done by PHP.

 

  • PHP will add a hidden input tag for every form that PHP finds in the HTML code. The hidden input tag will have the name PHPSESSID right after the <form> tag. The value will depend on what PHP assigns the session ID. 

 

Example:

<form>
	<input type="hidden" name="PHPSESSID" value="9496732321" >
</form>

 

By doing this, PHP can retrieve the session identifier when the form gets submitted and identify who it is communicating with.

 

  • Modify all the links in the HTML code such that they have a GET parameter added to the link itself. That GET parameter will also have the name of PHPSESSID, and the value will, of course, be the unique session identifier – so the PHP session ID will be a part of the URL query string.

Example:

<a href="http://www.codingninjas.com">Best learning website!<a/>

 

 Code modified to include the session ID:

<a href="http://www.codingninjas.com?PHPSESSID=96bb67abbg6th67d78ba0f678272926rd">Best learning website!<a/>

Security Considerations:

 

1. Session Hijacking: Protect against session hijacking by using secure connection protocols (e.g., HTTPS), setting proper session cookie settings (e.g., HttpOnly, Secure), and regenerating session IDs regularly.

2. Session Fixation: Prevent session fixation attacks by regenerating the session ID after a successful login or privileged action, and by avoiding the acceptance of session IDs from untrusted sources.

3. Cross-Site Scripting (XSS): Validate and sanitize user input stored in session variables to prevent XSS attacks. Use appropriate escaping techniques when outputting session data to HTML.

4. Sensitive Data: Avoid storing sensitive information, such as passwords or credit card numbers, directly in session variables. Instead, use secure storage mechanisms and encrypt sensitive data.

5. Session Expiration: Set an appropriate session expiration time to automatically log out users after a certain period of inactivity. This helps prevent unauthorized access to session data if a user forgets to log out.

6. Secure Session Storage: Ensure that session files are stored in a secure location on the server, with proper file permissions to prevent unauthorized access. Consider using secure session handlers or databases for session storage.

7. Session Logout: Provide a clear logout mechanism that destroys the session and invalidates the session ID. This helps prevent unauthorized access to the session after the user has logged out.

FAQs

How long is a PHP session?

A PHP session lasts until the browser is closed or until it has been inactive for a duration specified by the session timeout.

What is a session handler in PHP?

A session handler in PHP manages how session data is stored and retrieved, allowing customization of session storage mechanisms.

How to give session time in PHP?

Set session duration in PHP using ini_set('session.gc_maxlifetime', timeInSeconds); before the session starts.

What is the limit of a PHP session?

The limit of a PHP session is primarily determined by the server's storage capacity and the session.gc_maxlifetime setting.

Key Takeaways

Unlike cookies, a PHP session saves data (in the form of variables) on the server rather than the user's system, reusing it across multiple pages. Session variables are stored in the browser until the user closes it.

 

The session start() function must be called at the start of the page. Most sessions create a user key on the user's system. A new page then scans this to access that session; a new one is created if no match is found.

 

If you loved reading this article about PHP sessions, check out Why Use PHP programming in 2021? Its Pros and Cons and 5 Best Free PHP Projects With Source Code To Work In 2021.

Live masterclass