i have created one project in PHP, into which i am managing sessions.
I am creating session in my config.php file by writing following line of code.
session_start();
and to destroy this session, in logout.php file i have write following line.
session_destroy();
and i have not mention any code for session in any other project file, but the problem is session is active untill i call logout.php,
what i want is session should expire if user is inactive for 15 minutes.
can anyone help me for this, i am new to PHP, please give some example code or link to achieve this..
Use the session_unset() and session_destroy() Functions to Set the Session Timeout in PHP. We can use the session_unset() function to unset the $_SESSION variable at the run-time and use the session_destroy() function to destroy the session from the storage. The time() function returns the current time.
The timeout limit of the session can be set by setting the value of two directives in the php. ini file or using the ini_set() function in the PHP script. The directives are given below. It is used to set the time limit in seconds to store the session information in the server for a long time.
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.
Destroying a PHP Session A PHP session can be destroyed by session_destroy() function. This function does not need any argument and a single call can destroy all the session variables. If you want to destroy a single session variable then you can use unset() function to unset a session variable.
Call below function in your header file, so that whenever user does any activity at that time page gets refreshed and check whether session time outs or not.
function auto_logout($field)
{
$t = time();
$t0 = $_SESSION[$field];
$diff = $t - $t0;
if ($diff > 1500 || !isset($t0))
{
return true;
}
else
{
$_SESSION[$field] = time();
}
}
Use something like this in header
if(auto_logout("user_time"))
{
session_unset();
session_destroy();
location("login.php");
exit;
}
User_time is the session name. I hope this answer will help you. What actually this code does is : "Checks whether diff is greater than 1500 seconds or not. If not then set new session time." You can change time diff(1500) according to your requirement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With