expire certain cookies after specific amout of inactivity time - php

i wonder, how i can remove all certain cookies after (e.g. : 10 minutes) inactivity .
im working on securing a php project and one of the steps are this
i should remove administration cookies and session saved in mysql after certain amount inactivity time in php/mysql project
is there any suggestion !?

Well, you should never be storing anything important in cookies, so you should really only have a Session ID stored as a cookie.
Simply set that cookie to expire in 10 minutes. Store that same timestamp in your database.
After, say, 5 minutes, do what you need to do, then set the cookie to expire in another 10 minutes and update the session
After, say, 11 more minutes, the cookie won't be provided, and you can forward the user to your "not authenticated page".
In a cron job or on every page load, delete any sessions that have an expiry time in the past.

save a random string both in cookie and in db, in db also save the expire time..
when a client perform a request get the string from cookie and check the concerning expire time in db...
if time is passed destroy the cookie, otherwise not...
<?php
//retrive cookies if exist the hash stored in it.
//cookie don't exist save the cookie
if(!$_COOKIE){
//create a random string in $rnd_string and the expire date in $data
setcookie("hash", $rnd_string);
//sql connection here
//adding rows to db..
mysql_query("INSERT INTO table (expiredate, hash) VALUES ('".$data."','".$rnd_string."')");
}
else{
//here the code if cookie exist
$hash=$_COOKIE['hash'];
//sql connection here
//retrieving row from db
$result=mysql_fetch_array(mysql_query("SELECT expiredate FROM table WHERE hash='".$hash."'"));
//in $result['expiredate'] you'll have the expire date, check this with server time and decide if is session is valid or not...
}

Couldn't you just set the cookies on every page to expire in 10 * 60?

Related

How to call a function before the idle timeout session expiry in PHP

I have a large application which expires the session data after 30 minutes of idle time. Now I want to call a function before the session expiration.
My Reason for above question: I am storing a unique id in database for some purpose. When the user clicks logout, I will delete that ID. I want to delete that ID even when the user session expires after idle time.
As far as i know , it will be bad practice to set a "counter" for users to check if their session is expired.
If you need this ID to see who is connected in your administration aria , one possible way to do it is by checking the session expiration on loading admin page , and then delete the expired sessions rows then showing only active sessions.
So my idea is that while you are not using your admin dashboard it is okay that some sessions ID's still in your database , once you try to see who is online , the check function is called and clean up your data for expired session.
THAT IF YOU ARE USING THAT ID FOR SOMTHING LIKE THAT SINCE YOU DIDN''T SHARE THE WHOLE REASON OF WHY YOU NEED TO DO SO.

How to set expire time for specific session

I am working with Laravel. My question is in Laravel any way to manage specific session with specific expire time.
I extends session expire time from session.php but here it's apply on all session.
For example I want to manage Login session for 1 week or specific time and other session should be expire after 1 hour or normal time like close browser.
You could try saving date of session's assignment to user.
Let's have an example of a user name.
Having mysql table session of id,user_id,session_name and created_at you could simply do something like:
$s = new Session;
$s->user_id = $user_id;
$s->session_name = 'name';
Then later on in you app you could simply check if time between NOW and $s->created_at is greater than value you are interested in (like 7 days or so). If so - delete the record and delete session by doing:
session()->forget($s->session_name);
EDIT
You can also add a column of duration so you can dynamically forget sessions after time passed out.

Why are my session lifetimes not expiring when they're supposed to?

When my users login, I want to set the amount of time before the session expires.
I've accomplished this by setting the lifetime in session_set_cookie_params.
When I look at the cookie's expiration date it says:
Saturday, December 8, 3296 at 11:45:08 AM
But when I come back after an hour the cookie is there but my site won't recognize it. Why won't my site recognize or use the cookie?
Cookie contains only session identifier. The data itself is stored on server side. PHP periodically deletes expired sessions. When you're returning after one hour, session data is already lost and session ID from your cookie can't match to anything.
Chck out session.gc_maxlifetime (http://php.net/manual/en/session.configuration.php#ini.session.gc-maxlifetime) for more info.

PHP/MySQL Update database on session timeout

I'm working on a "flash website". In this program, I'd like to add an "Online Users" list, which relies on sessions: A session is started when a user logs in, and the user is marked as Online in the database. As soon as the logs out or closes the browser, the user is marked as Offline in the database.
I know that running some functions when the browser is closed will require Javascript, and it's not safe either: If the browser were to crash, the functions wouldn't run. That's why I've settled for the database updating if the user logs out or if the user's session times out.
I've been looking up session timeouts, and ran into this, along with many others like it marked as duplicates: How do I expire a PHP session after 30 minutes?
The problem with the answer's method is; It's a conditional sentence that checks if the user's last activity was X seconds ago, and if there was no activity, it times out. Useful in some websites, but useless for the Online Users list, since it updateds when a new request is sent, and since there won't be any requests after the user closes the browser.
Also mentioned in other answers is the use of session.gc_maxlifetime and session.cookie_lifetime, but the Best answer states that using them is a bad idea; One doesn't destroy the session, just the cookies, and the other is "cost-intensive".
What I want is the user to time out and the database to update and mark the user as Offline without using the If-Conditional sentence, or maybe with using a different If-conditional sentence that only has to be used once when the user logs in, like a timer or something, and whenever a request is sent, the timer restarts...those are just my ideas so far on how to solve this problem.
But, how do I do this? I'm sorry if the answer is something very simple and obvious, I'm very new to PHP.
Edit: Long Story Short:
I want to run a function after the user closes his browser, or is inactive for 20 minutes.
Clarification...
I want to update the database after 20 minutes of inactivity even if the browser has been closed.
I want to update the database after 20 minutes of the browser being
closed.
I don't think this is really possible to do with browsers being closed (reliably). If they click the logout button you can obviously run some code to mark the user as logged out. You can specify how long a session is good for with the functions you mentioned but all this does is makes the cookie be deleted on the client side, it doesn't trigger anything on the server side.
About the only thing you can do is track the time of the user's last activity and if they haven't had activity in a while assume they are gone. So just add a field to your user table and store a datetime or unix timestamp of their last activity. Then you can either run a cron job every few minutes that marks users as logged out or you can simply modify your SQL query to pull only users that have a last activity less than 20 minutes ago.
You can do this with the help of a online users table with last active field,
window.setInterval(function() {
$.ajax({
url: "http://yourdomain/updateLastactive/?uid=" + User_ID,
success: function(data) {
}
});
}, 5000); // 5 seconds
This page will update the current time-stamp as last active for that user
Then on online users query you can do like below,
SELECT UID FROM ONLINE_USERS WHERE LAST_ACTIVE > DATE_SUB(NOW(), INTERVAL 30 MINUTE));
if (!isset($_SESSION['CREATED'])) {
$_SESSION['CREATED'] = time();
} else if (time() - $_SESSION['CREATED'] > 1800) {
// session started more than 30 minutes ago
session_regenerate_id(true); // change session ID for the current session an invalidate old session ID
$_SESSION['CREATED'] = time(); // update creation time
}
Also read this
http://php.net/manual/en/session.configuration.php#ini.session.gc-maxlifetime
You want to catch the event by using the information here:
How to capture the browser window close event?
You will then need a page on the server that you call in that event handler with the sessionID.
That page calls a local script, page, or service that you set up to delay 20 minutes and expire the session. If you want to restart the clock if the user revisites before expiration, you will need to include a way to interrupt or cancel that script's process and you will need to retain the SessionID in a cookie which will need to be looked for upon every page load. If the cookie's SessionID is found and matches, the timeout gets interrupted/stopped (if it's still going). If it already completed, a new SessionID will need to be issued.
If you have a lot of these cancellations at the same time, you will instead queue them up on the server and have a process periodically check the queue and expire them as needed.
The way most sites avoid all this is to set a 30 minute or whatever session timeout that is enforced whether the visitor is active or not.
The easiest way to do this is to write a MySQL stored procedure that looks at the session timestamp and deletes the session data when it is > 20min old. You can also do it as an external cron job, but a stored procedure would be better.
In addition, you need to refresh the session timestamp every time the user connects.
If you want to make sure you don't delete a session when the user still has your 'page' open, then some background JavaScript refresh to your site will function as a keep-alive. Note that if the user closes the 'window' or 'tab', it will be the same as the whole browser being closed - I'm not sure you can do anything about this.
Of course, you to do this, you need to store your sessions in MySQL.
TL;DR
MySQL stored procedure or cron job deletes session if session_timestamp > 20min
Client-side Javascript does ajax refreshes to keep session open
Session timestamp updated every time the 'page' is requested (browser or ajax).

Understanding Session Time-out (php)

I need to delete old user datas in the DB, if user session is timeout.
How can I solve this problem with using PHP?
You can store the session_key with the rows in the database, and then define a time limit yourself. And then create a cronjob that delete's all rows with session_key's that has not been used within your limit.
A default session last until the browser is closed, so you cant know how many seconds that the session is active. Even when the session is closed, the session will not be deleted until the garbage collector removes it.
You can set the time for session time out . say 30 mins.
sesssion_gc_maxlifetime
You can check the login time of a user .
But if you want to delete the data , better to keep session in DB or at least
keep a status , login or logout and login time and logout time in the DB
It will be safe
So you can delete the data based on login time and current timedifference
set a cron job run in 30 mins or whatever time you wish
There is no way to add code to run when the session times out. You'll have to come up with a scheme yourself.
I'd suggest adding a timestamp to your database records and updating it every time the data is accessed. Then have a script via cron go through the records and delete those that are older than the session timeout.

Categories