What is a session? How does the session work In PHP?
Its a Global variable to be used across multiple pages for authenticating a particular user.
It creates a 32-digit hexadecimal string named PHPSESSID in Server. When the User navigates the page it will match this ID with the Session ID to recognize the same user.
Session variables are stored in an associative array called $_SESSION[].
Start the session
1 2 3 | <?php session_start(); ?> |
Set Session variable
1 | $_SESSION["Car"] = "Hyundai"; |
Remove all session variables
1 2 3 | <?php session_unset(); ?> |
Here is the example to unset a single variable
1 2 3 | <?php unset($_SESSION['Car']); ?> |
Here is the call which will destroy all the session variables
1 2 3 | <?php session_destroy(); ?> |
The default session time in PHP is 24 minutes (1440 seconds).
We can change the time in php.ini
1 | session.gc_maxlifetime = 1440 |
Or
In PHP file you can do the below like
1 | ini_set('session.gc_maxlifetime', 3600); |
Questions Asked in Interview About Session In PHP
- What is Session
- How to store a variable in Session
- How to destroy Session
- What is the default time for a session