How to change the session timeout in PHP?
In PHP, sessions are maintained to check if the user is active. When the user becomes inactive and the user forgets to logout from the web page, there is a chance of other users viewing the page causing security breach. By default, a session in PHP gets destroyed when the browser is closed. Session timeout can be customized, to make the user’s page inactive after a fixed time.
Starting session: The PHP, session_start() function is used to start a session in the web page.
Session variables: After the start of the session, session variables can be created for future use. Session variables can be created and the values can be stored in those variables as follows:
- Creating session variable with variable name ‘var1’ and assigning the value of ‘5’ to it can be done as:
- Assigning a variable to a session variable can be done as:
Destroying session variables and session: To remove all session variables that are initialized before destroying the session, the following command should be used:
- To destroy the certain session, the following command should be used:
- To destroy the complete session, the following command should be used:
Changing session timeout: Considering there’s a login page with the ‘Login’ button in an HTML form. When the user clicks on the ‘Login’ button, session starts and session variables are set. A session variable to store the time of login is initialized. It is then directed to the home page of the user.
- Login page:
On the home page, to maintain the session, the session_start() function is called. This enables us to retrieve session variables from this page. Using time() function, the current time can be calculated. The difference between the current time and the session variable created at the time of login should not exceed the desired timeout. When the duration exceeds, the session is destroyed and the page is redirected to the Login page.
Like if the Session timeout=10 minutes. The session should automatically destroy after 10 minutes = 10*60 seconds = 600 seconds
- Home Page: