session_destroy() after certain amount of time in PHP - php

I am currently saving a session in my form page:
$testingvalue = "SESSION TEST";
$_SESSION['testing'] = $testingvalue;
On another page I am calling the session to use the value:
<?php
session_start(); // make sure there is a session
echo $_SESSION['testing']; //prints SESSION TEST???
?>
Now I want to use the
session_destroy();
to destroy the session. But what I would like to do is destroy the session after 2 hours have been passed.
Any idea on how to do it and also where should I put it?
I have something like this:
<?php
session_start();
// 2 hours in seconds
$inactive = 7200;
$session_life = time() - $_session['testing'];
if($session_life > $inactive)
{
session_destroy();
}
$_session['testing']=time();
echo $_SESSION['testing']; //prints NOTHING?
?>
Will that work?
If I am inactive for more than 2 hours this should be blank?:
echo $_SESSION['testing'];

Something like this should work
<?php
// 2 hours in seconds
$inactive = 7200;
ini_set('session.gc_maxlifetime', $inactive); // set the session max lifetime to 2 hours
session_start();
if (isset($_SESSION['testing']) && (time() - $_SESSION['testing'] > $inactive)) {
// last request was more than 2 hours ago
session_unset(); // unset $_SESSION variable for this page
session_destroy(); // destroy session data
}
$_SESSION['testing'] = time(); // Update session

you need a static start time to expire. $session_life > $inactive will always be greater no matter what.
session_start();
$testingvalue = "SESSION TEST";
$_SESSION['testing'] = $testingvalue;
// 2 hours in seconds
$inactive = 7200;
$_SESSION['expire'] = time() + $inactive; // static expire
if(time() > $_SESSION['expire'])
{
$_SESSION['testing'] = '';
session_unset();
session_destroy();
$_SESSION['testing'] = '2 hours expired'; // test message
}
echo $_SESSION['testing'];
or session-set-cookie-params

Related

Why count($_COOKIE) > 0 returns 'true' case while all cookies are deleted?

I am trying to delete a cookie by setting that cookie in past time:
$cookie_name = "user";
$cookie_value = "david";
//subtraction from time causes deletion of cookie
setcookie($cookie_name, $cookie_value, time() - (86400 * 30), "/");
With the below code I try to check whether cookie is enabled or not and it returns if case rather than else part, while I already dell that cookie:
//counting number of cookies
if(count($_COOKIE) > 0) {
echo "<br>Cookies are enabled/exists";
} else {
echo "<br>Cookies are disabled/not exists";
}
But the else part is not working when we delete cookie and I don't know why?
The main problem is you just set user cookie time to past date not all the other cookie in super global $_COOKIE array . Try like this way to set for all $_COOKIE value using foreach() to past date and then check count condition.
<?php
$cookie_name = "user";
$cookie_value = "david";
$past_time = time() - 3600;
//use look set all cookie time to past date.
foreach ( $_COOKIE as $key => $value )
{
setcookie( $key, $value, $past_time, '/' );
}
//counting number of cookies
if(count($_COOKIE) > 0) {
echo "<br>Cookies are enabled/exists";
} else {
echo "<br>Cookies are disabled/not exists";
}
?>
DEMO: https://3v4l.org/jvRXW

How to use Cookies to count visits in PHP?

I am new to PHP and I am having quite the trouble with using Cookies!
So I am trying to have one cookie that will keep count of the number of times the page has been loaded within a lifetime of 1 minute. Once it has reached its lifetime it needs to be unset and the counter should go back to 0.
So far here is what I have:
At the top of the Php file
<?php
session_start();
$_SESSION['user_start'] = time();
$cookie_name = "counter";
$cookie_value = 0;
setcookie($cookie_name, $cookie_value);
?>
<html>
<body>
<?php
if (time() - $_SESSION['user_start'] < 60) {
$counter = $_COOKIE[$cookie_name] +1;
setcookie($cookie_name, $counter);
echo "Value is: " . $_COOKIE[$cookie_name];
}
else{
unset($_SESSION['user_start']);
unset($_COOKIE[$cookie_name]);
}
?>
It's a little odd - but this should do the trick, I'm storing both the counter value and the expiry time in a cookie in JSON format. That way you can just increment the counter whilst keeping the initial expiry time (e.g. 1 minute after the initial request).
<?php
$counter = 0;
$expires = time()+60;
if(isset($_COOKIE['counter'])) {
$data = json_decode($_COOKIE['counter']);
$counter = ++$data->counter;
$expires = $data->expires;
}
$jsonData = json_encode(['counter' => $counter, 'expires' => $expires]);
setcookie("counter", $jsonData, $expires);
echo $counter;

how to make user logout after 30 mins of inactivity?

I am using sessions for user login & logout. I have a requirement that after 30 minutes of user inactivity he/she has to logout automatically. I searched & tried few solutions but didn't work though. I tried below solutions:
Solution1:
if(time() - $_SESSION['timestamp'] > 900) { //subtract new timestamp from the old one
echo"<script>alert('15 Minutes over!');</script>";
unset($_SESSION['email'], $_SESSION['user_id'], $_SESSION['timestamp']);
session_destroy();
$_SESSION['logged_in'] = false;
header("Location: " . index.php); //redirect to index.php
exit;
} else {
$_SESSION['timestamp'] = time(); //set new timestamp
}
Solution2:
function auto_logout($field)
{
$t = time();
$t0 = $_SESSION[$field];
$diff = $t - $t0;
if ($diff > 3000 || !isset($t0))
{
return true;
}
else
{
$_SESSION[$field] = time();
}
}
if(auto_logout("email"))
{
session_unset();
session_destroy();
header('Location: index.php');
exit;
}
Neither of them worked, Could any one please tell me how to track last activity of user and check that time with the current time if exceeds 30 minutes and make that user logout?
I think this may help : How do I expire a PHP session after 30 minutes?
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
// last request was more than 30 minutes ago
session_unset(); // unset $_SESSION variable for the run-time
session_destroy(); // destroy session data in storage
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
If you want to find the activity , you can use the javascript as below and then redirect to logout page to clear the session . here i put 5 sec of inactivity
var t;
window.onload = resetTimer();
// DOM Events
document.onmousemove = resetTimer();
document.onkeypress = resetTimer();
console.log('loaded');
function logout() {
alert("You are now logged out.")
//location.href = 'logout.php'
}
function resetTimer() {
clearTimeout(t);
t = setTimeout(logout, 5000)
}

How to set Session Timeout in php?

I'm still new in PHP language and trying out on how to set Session Timeout, which ensure that when user log in to their account, it will limit to few minutes / 1 hour before the account got logout automatically when user log in too long. I refered to this link.
http://bytes.com/topic/php/insights/889606-setting-timeout-php-sessions
index.php
<?php
if(!isset($_SESSION))
{
session_start();
}
$timeout = $_SERVER['REQUEST_TIME'];
/**
* for a 1 minute timeout, specified in seconds
*/
$timeout_duration = 60;
if (isset($_SESSION['LAST_ACTIVITY']) && ($timeout - $_SESSION['LAST_ACTIVITY']) > $timeout_duration) {
session_unset();
session_destroy();
session_start();
}
$_SESSION['LAST_ACTIVITY'] = $timeout;
?>
coupon.php
<?php
// error_reporting(E_ALL); ini_set("display_errors", 1);
session_start();
$timeout = 60; // Number of seconds until it times out.
// Check if the timeout field exists.
if(isset($_SESSION['timeout'])) {
$duration = time() - (int)$_SESSION['timeout'];
if($duration > $timeout) {
// Destroy the session and restart it.
session_destroy();
}
}
// Update the timeout field with the current time.
$_SESSION['timeout'] = time();
// include ('sessionTimeout.php');
if( !isset($_SESSION["loginSuccess"]) ){
echo "<script type='text/javascript'>alert('Login failed!');</script>";
die('<meta http-equiv="refresh" content="0;URL=\'login-redirect.php\'" />');
}
?>
sessionTimeout.php
<?php
function session_start_timeout($timeout=5, $probability=100, $cookie_domain='/') {
// Set the max lifetime
ini_set("session.gc_maxlifetime", $timeout);
// Set the session cookie to timout
ini_set("session.cookie_lifetime", $timeout);
$seperator = strstr(strtoupper(substr(PHP_OS, 0, 3)), "WIN") ? "\\" : "/";
$path = ini_get("session.save_path") . $seperator . "session_" . $timeout . "sec";
if(!file_exists($path)) {
if(!mkdir($path, 600)) {
trigger_error("Failed to create session save path directory '$path'. Check permissions.", E_USER_ERROR);
}
}
ini_set("session.save_path", $path);
// Set the chance to trigger the garbage collection.
ini_set("session.gc_probability", $probability);
ini_set("session.gc_divisor", 100); // Should always be 100
// Start the session!
session_start_timeout(60, 10);
if(isset($_COOKIE[session_name()])) {
setcookie(session_name(), $_COOKIE[session_name()], time() + $timeout, $cookie_domain);
}
}
?>
logout.php
<?php
session_start();
include('config.php');
foreach($_SESSION as $key => $value){
if (strpos($key, $PROJECT_NAME) !== FALSE){
unset($_SESSION[$key]);
}
}
$_SESSION[$PROJECT_NAME . 'logout'] = true;
session_destroy();
//print_r($_SESSION);
header('Location:' . $base_url . 'index');
?>
Am i missing out something? This is because my session timeout doesn't work.
Start a Javascript timer when the page loads and redirect the user to the logout page when the timer expires.
<script type="text/javascript">
setTimeout(function() { window.location.href = "logout.php"; }, 60 * 60 * 1000);
</script>

Automatic session timeout

I need to set, automatic session time out after some fixed time in my site.
I used the script below but it's not working properly.
I set the some time but it automatically times out before that time.
if((empty($Session_UserId)) || (empty($Session_Username)))
header("Location:index.php");
if($_SESSION['session_count'] == 0) {
$_SESSION['session_count'] = 1;
$_SESSION['session_start_time']=time();
} else {
$_SESSION['session_count'] = $_SESSION['session_count'] + 1;
}
$session_timeout = $logout_sec; // 30 minute (in sec)
$session_duration = time() - $_SESSION['session_start_time'];
if ($session_duration > $session_timeout) {
session_unset();
session_destroy();
session_start();
session_regenerate_id(true);
$_SESSION["expired"] = "yes";
header("Location:index.php"); // Redirect to Login Page
} else {
$_SESSION['session_start_time']=time();
}
I think what people are trying to say is, try the code below. which is a copy/paste of your code just without the last else statement.
if((empty($Session_UserId)) || (empty($Session_Username)))
header("Location:index.php");
if($_SESSION['session_count'] == 0) {
$_SESSION['session_count'] = 1;
$_SESSION['session_start_time']=time();
} else {
$_SESSION['session_count'] = $_SESSION['session_count'] + 1;
}
$session_timeout = $logout_sec; // 30 minute (in sec)
$session_duration = time() - $_SESSION['session_start_time'];
if ($session_duration > $session_timeout) {
session_unset();
session_destroy();
session_start();
session_regenerate_id(true);
$_SESSION["expired"] = "yes";
header("Location:index.php"); // Redirect to Login Page
}
The problem with your code is the last if/else construct. Because if the session has not been timed out, the session start time is set to the current time. So this is rather a “last activity” time stamp. If you drop the else block, the session will not be usable longer than your time out.

Categories