How to set Session Timeout in php? - 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>

Related

Session ID cannot be deleted

I am trying to create a login system. At the moment everything seem to be working as expected except I am not able to clear my session ID,
why do session_unset() and session_destroy don't seem to have any effect ?
UPDATE: solved below
INDEX.PHP
session_start();
if (array_key_exists('id', $_COOKIE) && $_COOKIE ['id']) {
$_SESSION['id'] = $_COOKIE['id'];
print("SESSION ID");
print("<br>");
print_r($_SESSION);
print("<br>");
print("COOKIE");
print("<br>");
print_r($_COOKIE);
}
// SET SESSION
function setSession($setSessionData) {
$_SESSION['id'] = $setSessionData[0];
if ($setSessionData[1] == 'yes') {
setcookie('id', $setSessionData[0], time() + 60*60*24*365, '/' );
}
};
// CLEAR SESSION
function unSetSession() {
session_unset();
setcookie("id", "", time() - 60*60*24*365, '/');
session_destroy();
}
SOLVED:
Had to initialise the session in my function called via Ajax; so the logout function is like so:
function unSetSession() {
session_start();
$_SESSION = array();
setcookie("id", "", time() - 60*60*24*365, '/');
session_destroy();
}

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)
}

Why is my session not working when I try to count IP hits?

I'm trying to create a counter in PHP that will count how many times within a set timeframe an IP can visit a page and when it hits a download counter within that timeframe it re-directs. The approach I've seen recommended was doing this with a session after referencing several Q&As:
PHP function to increment variable by 1 each time
How to not increase page/post view count with refresh?
php increment variable value with 1 when submit
I also looked at:
How do I count unique visitors to my site?
adding counter to php page to count the unique visitors
I do not have much experience with cookies and sessions so I believe that is where I fault in my code. If you have any suggestions on better implementation than what I am doing please advise.
The code:
$jsonFile = 'foobar.json';
$theJSON = file_get_contents($jsonFile);
$jsonArray = json_decode($theJSON, true);
$theIP = "123.123.123"; // $_SERVER['REMOTE_ADDR']
$thisTime = date("H:i");
$addMin = 1; // set value for testing purposes
$addHour = 0; // set value for testing purposes
$downloadHits = 5; // set value for testing purposes
$timeLater = date("H:i", strtotime($thisTime)+(($addMin*60)+($addHour*60*60)));
if (!empty($theIP) && !empty($jsonArray)) {
foreach ($jsonArray as $value) {
if (in_array($theIP, $value, true)) {
echo "yes"; // header('Location: https://www.url/darthvader.com');
exit();
} else {
if ($thisTime <= $timeLater) { // where my issue starts
echo $timeLater; // for testing
session_start();
$counter = $_SESSION['promo_number'];
$counter++;
if ($counter == $downloadHits && file_exists($jsonFile)) {
$currentData = file_get_contents($jsonFile);
$currentArray = json_decode($currentData, true);
$theStuff = array(
'ip' => "123.123.123", // $_SERVER['REMOTE_ADDR']
'date' => date("H:i"),
'time' => date("m.d.y")
);
$currentData[] = $theStuff;
$finishData = json_encode($currentData);
} else {
echo 'bar'; // for testing
session_unset();
session_destroy();
}
}
}
}
} else {
echo '<span style="color:red; font-weight:bold;">empty file</span>';
}
What I am trying to do is count the times an IP visits a post within a set time and if it hits that count redirect the IP. I do know that the IP can be spoofed and I am not worried about that plus I would prefer to not use a database at this time. So how can I properly set a session to count the hits and if the IP hits the post in set count it redirects the IP?
EDIT:
After doing some reading and the help from the comment and answer I've made an edit that I hope explains what I am trying to do. After researching further I ran across:
session_destroy() after certain amount of time in PHP
How do I expire a PHP session after 30 minutes?
which led me to code:
session_start();
$jsonFile = 'foobar.json';
$jsonArray = json_decode(file_get_contents($jsonFile), true);
$theIP = $_SERVER['REMOTE_ADDR'];
$addMin = 2; // set value for testing purposes
$addHour = 0; // set value for testing purposes
$targetedHits = 1; // set value for testing purposes
$timeLater = time() + ($addMin*60) + ($addHour*60*60);
$_SESSION['expire'] = $timeLater;
if (!empty($theIP) && !empty($jsonArray)) {
//look for the $theIP
if (in_array($theIP,array_column($jsonArray,'ip'))) {
echo 'IP found in json';
exit;
}
// look at the time the session was set, add to counter or delete session
if ($_SESSION['count'] = isset($_SESSION['count']) && time() < $_SESSION['expire'] ) {
echo 'adding to count';
$_SESSION['count'] + 1;
// limit reached. Add IP to blacklist
if ($_SESSION['count'] > $targetedHits) {
echo 'session count reached max';
$jsonArray[]=[
'ip' => $theIP,
'date' => date("H:i"),
'time' => date("m.d.y")
];
// save changes
file_put_contents($jsonFile,json_encode($jsonArray));
session_destroy();
exit;
}
} elseif (time() > $_SESSION['expire']) {
echo 'nuking session and counter';
session_destroy();
} else {
echo 'setting count to 1';
$_SESSION['count'] = 1;
}
}
echo '<pre>';
var_dump($_SESSION);
echo '</pre>';
But sadly now the $_SESSION['count'] + 1; no longer increments.
Darth_Vader you're almost there. There are a couple of issues with your script.
You never save the count in session, so you have no way to retrieve it later
You start your session late in the script. This is poor practice because it will break as soon as you echo something higher up or forget and try to use $_SESSION higher up
You read your JSON file and decode it twice unnecessarily, wasting system memory
You never save the changes you make to the JSON
You call session_unset() and session_destroy() after a successful download, so the count would be lost even if you were trying to save it properly
My modifications:
session_start();
$jsonFile = 'foobar.json';
$jsonArray = json_decode(file_get_contents($jsonFile), true);
$theIP = $_SERVER['REMOTE_ADDR'];
$thisTime = time();
$addMin = 1; // set value for testing purposes
$addHour = 0; // set value for testing purposes
$downloadHits = 5; // set value for testing purposes
$timeLater = $thisTime + ($addMin*60) + ($addHour*60*60);
if(empty($theIP)){
echo 'empty file';
exit;
}
//look for the $theIP in the 'ip' column
if(in_array($theIP,array_column($jsonArray,'ip'))){
echo 'IP found in json';
exit;
}
if($thisTime > $timeLater){//not sure what you want to do here
exit;
}
//increment the count, or set it to 1 to begin
$_SESSION['count'] = isset($_SESSION['count'])? $_SESSION['count']+1 : 1;
if($_SESSION['count']>=$downloadHits){//limit reached. Add IP to blacklist
$jsonArray[]=[
'ip' => $theIP,
'date' => date("H:i"),
'time' => date("m.d.y")
];
//save changes
file_put_contents($jsonFile,json_encode($jsonArray));
exit;
}
echo 'good to go!'; //allow the download
Happy coding.
Figured it out after spending some time under the session tag. These two questions were helpful:
How do check if a PHP session is empty?
How can I clear my php session data correctly?
Which led me to code:
session_start();
$jsonFile = 'foobar.json';
$jsonArray = json_decode(file_get_contents($jsonFile), true);
$theIP = $_SERVER['REMOTE_ADDR'];
$addMin = 1; // set value for testing purposes
$addHour = 0; // set value for testing purposes
$targetedHits = 5; // set value for testing purposes
$timeLater = time() + ($addMin*60) + ($addHour*60*60);
if (empty($_SESSION['count'])) {
$_SESSION['expire'] = $timeLater;
}
if (!empty($theIP) && !empty($jsonArray)) {
// look for the $theIP
if (in_array($theIP,array_column($jsonArray,'ip'))) {
$_SESSION['count'] = 0;
session_destroy();
echo 'IP found in json';
exit;
}
if (time() < $_SESSION['expire']) {
echo 'below the time ';
$_SESSION['count'] = isset($_SESSION['count'])? $_SESSION['count'] + 1 : 1;
if ($_SESSION['count'] > $targetedHits) {
echo 'session count reached max ';
$jsonArray[] = [
'ip' => $theIP,
'date' => date("H:i"),
'time' => date("m.d.y")
];
// save changes
file_put_contents($jsonFile,json_encode($jsonArray));
unset($_SESSION['count']);
session_destroy();
exit;
}
} elseif (time() > $_SESSION['expire']) {
echo 'nuking session and counter';
$_SESSION['count'] = 0;
unset($_SESSION['expire']);
}
}
echo '<pre>';
var_dump($_SESSION);
echo '</pre>';
I hope the above helps the next person because I didn't really know anything about sessions and it has been an adventure getting this to work this evening.

session_destroy() after certain amount of time in 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

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