Introduction to Session in PHP
Session in PHP is a global array. We don’t need global keyword, sessions are automatically accessible throughout the project’s scope. It is stored in a temporary file named php.ini, on the server.
When we open a website, do some work there and then close it. It’s much like a session. The Session is used to store the user information across multiple pages it is much like cookies, but there are a couple of differences, first one is when we close browser the session will destroy but cookies will not and the second difference is session is stored on the server and just place an id in user’s PC until he closes the website.
Why we use session:
Most of the time sessions are used in user authentication systems where we have to remember a user whether he is logged-In in that browser and when he logs out from the site the session will destroy.
How to create a session:
To create a session in PHP session_start() function is used.
1 2 3 |
<?php session_start(); ?> |
How to set session variable:
To set session variable session used global variable $_SESSION[ ];
1 2 3 4 |
<?php session_start(); $_SESSION["user"] = "Usman"; ?> |
Hot to get session value:
To get the value from the session we just have to save session variable in any variable.
1 2 3 4 5 |
<?php session_start(); $value = $_SESSION["user"]; echo $value; ?> |
How to destroy a session:
To destroy a session, session_destroy() is a function used to destroy all the active session variables.
1 2 3 |
<?php session_destroy(); ?> |
session_unset() also does the same thing.
Set a timeout time for the session:
By default the session timeout time is 20 minutes, but we set it according to over choice.
1 2 3 4 5 |
<?php session_start(); $_SESSION['start_time'] = time(); $_SESSION['end_time'] = $_SESSION['start'] + (30 * 60); ?> |
Now you have to check the session time in some other or in the same file.
1 2 3 4 5 6 7 |
<?php $time_now = time(); if($time_now > $_SESSION['end_time']) { session_destroy(); } ?> |
How to unset a session variable:
unset() function is used to unset a session variable, you just need to pass a session variable in order to unset a session variable.
1 2 3 |
<?php unset($_SESSION["user"]); ?> |
How to check the session variable:
isset() function is used to check whether the index of session array is set or not. It is commonly used in if else statements.
1 2 3 4 5 6 |
<?php if(isset($_SESSION["user"])) { $username=$_SESSION["user"]; //getting the value of session in a variable } ?> |