Destroying session PHP - php

I am using this code to end session after 10 seconds of inactivity:
ini_set('session.gc_maxlifetime', 10);
session_start();
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 10)) {
session_unset();
session_destroy();
}
$_SESSION['LAST_ACTIVITY'] = time();
It's works only when I refresh page after 10 seconds of inactivity. If I not refresh page or close my browser the session will never be destroyed. Could someone help me how to fix this?

Thanks for advices.
Now I am using also this javascript code to refresh after 10 seconds of inactive and it works good. But when I close browser session still will not be destroyed.
<body onmousemove = "canceltimer()"; onclick = "canceltimer()">
<script type="text/javascript">
var tim = 0;
function reload () {
tim = setTimeout("location.reload(true);",10000);
}
function canceltimer() {
window.clearTimeout(tim);
reload();
}
</script>

After 10 seconds, you need to destroy the session, then redirect them, like this:
session_destroy();
header("Location: logoutpage.php");
This will "refresh" the page and destroy the session.
Sorry about me not clarifying, but you will need an ajax call, here is a similar question. I will post the ajax in a moment. Sorry.
Unset session after some time
here is the ajax...set the timeout to your specified time. Again, sorry for not clarifying.
function refresh() {
$.ajax({
type: 'GET', // can be POST or GET
url: 'page.php' // php script to call
// when the server responds
}).done(function(response) {
console.log(response);
// call your function automatically
setTimeout(refresh, 5000);
});
}
Basically, the function refresh get called every 5000 milliseconds.

Related

How can I session destroy when user close the page?

These codes work but when I click somewhere (link or button), redirected to logout.php
var s= 0;
jQuery(function(){
jQuery(window).bind('beforeunload', function () {
if (s == 0) {
$.ajax({
async: false,
url: 'logout.php'
});
}
s++;
});
});
You could put in your session a variable with time() inside and use it as a short expiry limit, and while the user is inside your page do continous ajax calls to a php that updates the expiry. At the top of your page put:
session_start();
if(isset($_SESSION['expiry']))
if(time() > $_SESSION['expiry']){
session_destroy();
header("Refresh:0");
die();
}
$_SESSION['expiry'] = time()+20;
keep_alive.php
session_start();
$_SESSION['expiry'] = time()+20;
And in your js ping keep_alive.php with ajax every 10 seconds. If the user closes the page and doesen't rapidly reopen it loses his session

disable page refresh on lose focus

I am wondering if there is a way to disable an automatic page refresh when a page loses focus. I have it setup to refresh when it gains focus again already using this:
window.onblur= function() {window.onfocus= function () {location.reload(true)}};
that I found from here. I originally had the page auto refresh by using:
<meta http-equiv="refresh" content="60"/>
Which reloads the page every 60 seconds regardless of state.
I want to make the page have the auto refresh only when in focus with the initial refresh coming when the page gains focus again. After the gain of focus it should refresh at the time interval until focus is lost.
Thanks
You can't override this kind of refresh, you should probably use a JS timer to refresh, something like this (after removing the <meta http-equiv="refresh" content="60" /> tag):
var hasFocus;
window.onblur = function() {
hasFocus = false;
}
window.onfocus = function(){
hasFocus = true;
}
setInterval(reload, 60*1000);
function reload(){
if(hasFocus){
location.reload(true);
}
}
I ended up modifying the code from Mostafa Torbjørn Berg to maintain the refresh on focus and have the page automatically refresh every 60 seconds while the page has focus.
var hasFocus= true;
window.onblur = function() {
hasFocus = false;
}
window.onfocus = function(){
location.reload(true);
}
setInterval(reload, 60*1000);
function reload(){
if(hasFocus){
location.reload(true);
}
}

Change SESSION variable to stop "while loop"

I'm new to php and I want to control a php while loop script, using buttons (start/stop), the start button make an ajax call to the start.php script that define $_SESSION['loop'] = TRUE and execute the loop, the stop button make an ajax call to the stop.php script that just change $_SESSION['loop'] to FALSE.
Below is my code so far, but when I hit the stop button I became the alert (success stop) only after the while loop finish looping, which mean the loop didn't break as I was assuming.
I think it's something with the session that is locked while the loop is executing. If so, how to change the $_SESSION['loop'] value and make the loop read that value each time?
index.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#start').click(function(){
$.ajax({
url: "start.php"
});
});
$('#stop').click(function(){
$.ajax({
url: "stop.php",
success: function(){
alert('success stop');
},
error: function(){
alert('failure stop');
}
});
});
});
</script>
<button id="start">Start</button>
<button id="stop">Stop</button>
start.php
<?php
session_start();
$_SESSION['loop'] = TRUE;
ini_set('max_execution_time', 300);
$i = 0;
while($i < 100) {
if ($_SESSION['loop'] == TRUE) {
//query to save some variables
// Pause 10s after saving 2
if ($i != 0 && $i%2 == 0) {
sleep(10);
}
$i++;
} else {
break;
}
}
?>
stop.php
<?php
session_start();
if(isset($_SESSION['loop'])) {
$_SESSION['loop'] = FALSE;
}
?>
Your start and stop operations are in two different sessions, so changing $SESSION in one makes no difference to the other.
I think, you should use multi-threading for doing such things.
Please take some time to read it:
"Session data is usually stored after your script terminated without the need to call session_write_close(), but as session data is locked to prevent concurrent writes only one script may operate on a session at any time."
http://php.net/manual/en/function.session-write-close.php
Hence, it appears that $_SESSION['loop'] is written to session file at the end.
If you want to explicitly write data to session file, add session_write_close after $_SESSION['loop'] = TRUE. Note, if you need to read/write some session data again in the same script, you need to start the session and then read/write data.

jquery progressbar - loads all at once

I'd like to have a jQuery progress bar that updates based on the status of the server side request. I'm basing this code off of this tutorial but it uses a file uploader as its base (same as this question). I can't get it to work quite the same without the file uploader. The problem is that the progress bar only updates after process.php is done. Rather than asynchronously asking for an update on the progress, it waits for the whole process to be done. I only see the data: data alert once.
Any ideas?
Webpage:
<form id="upload-form" action='process.php' method="post" target="upload-frame">
<input type="hidden" id="uid" name="UPLOAD_IDENTIFIER" value="<?php echo $uid; ?>" >
<input type="submit" value="Submit" />
</form>
<div id="progressbar"></div>
<iframe id="upload-frame" name="upload-frame" style="display:none"></iframe>
Process.php - called when form is submitted
<?php
session_start();
$varArray=array(1,2,3,4);
$_SESSION['total']=count($varArray);
foreach($varArray as $val){
$_SESSION['current']=$val;
sleep(2);
}
?>
javascript
$(document).ready(function() {
var started = false;// This flag determines if the upload has started
$(function() {
// Start progress tracking when the form is submitted
$('#upload-form').submit(function() {
$('#progressbar').progressbar();// Initialize the jQuery UI plugin
// We know the upload is complete when the frame loads
$('#upload-frame').load(function() {
// This is to prevent infinite loop
// in case the upload is too fast
started = true;
// Do whatever you want when upload is complete
alert('Upload Complete!');
});
// Start updating progress after a 1 second delay
setTimeout(function() {
// We pass the upload identifier to our function
updateProgress($('#uid').val());
}, 1000);
});
});
function updateProgress(id) {
var time = new Date().getTime();
// Make a GET request to the server
// Pass our upload identifier as a parameter
// Also pass current time to prevent caching
$.ajax({
url: 'getProgress.php',
type: "GET",
cache: false,
data: {'uid':id},
dataType: 'text',
success: function(data){
alert("data: " + data);
var progress = parseInt(data, 10);
if (progress < 100 || !started) {
// Determine if upload has started
started = progress < 100;
// If we aren't done or started, update again
updateProgress(id);
}
// Update the progress bar percentage
// But only if we have started
started && $('#progressbar').progressbar('value', progress);
}
});
}
}(jQuery));
getProgress.php - called by the ajax request:
<?php
session_start();
if (isset($_REQUEST['uid'])) {
if (isset($_SESSION['total']) && isset($_SESSION['current'])) {
// Fetch the upload progress data
$total = $_SESSION['total'];
$current = $_SESSION['current'];
// Calculate the current percentage
$percent_done = round($current/$total*100);
echo $percent_done;
}else{
echo 100;// If there is no data, assume it's done
}
}
?>
AFAIK, PHP sessions are actually synchronous. That means that the Process.php script is blocking the getProgress.php script from running until Process.php is done with the session.
So what happens is:
Process.php starts and calls session_start ()
The server gives session control to session_start ()
getProcess.php starts and calls session_start ()
The server blocks getProcess.php until the session is unused.
Process.php completes and closes the session.
The server resumes getProcess.php and gives it control over the session.
getProcess.php now sees that the process is complete.
See http://www.php.net/manual/en/function.session-write-close.php.
Session data is usually stored after your script terminated without the need to call session_write_close(), but as session data is locked to prevent concurrent writes only one script may operate on a session at any time. [...]
I haven't tested the following code since I don't have access to a server at the moment but I imagine somethin like it should work:
<?php
$varArray=array(1,2,3,4);
session_start();
$_SESSION['total']=count($varArray);
session_write_close ();
foreach($varArray as $val){
session_start();
$_SESSION['current']=$val;
session_write_close ();
sleep(2);
}
?>

read data returned from jquery .post

I have a page that I want redirected to the login page if a user is inactive for 1/2 hour. I am new to jQuery and it has taken me awhile to get this far.
So basically the user logs in they are redirected to the home page. I have jQuery running on the home page that posts to the check_time.php page every 10 seconds. if they have been inactive for more than a 1/2 hour, then session is destroyed and they get redirected to the login page.
I have everything working except checking the value of the "data" that is returned from the check_time.php page.
here is the code on the home page.
ini_set('session.gc_maxlifetime',1800);
ini_set('session.gc_probability',1);
ini_set('session.gc_divisor',1);
session_start();
if($_SESSION['admin_login'] != $password){
header('Location: index.php');
exit();
}
if(isset($_SESSION['last_activity']) && (time()-$_SESSION['last_activity'] >1800)){
// last request was more than 30 minates ago
session_destroy(); // destroy session data in storage
session_unset(); // unset $_SESSION variable for the runtime
header('Location: index.php');
exit();
}
$_SESSION['last_activity'] = time(); // update last activity time stamp
?>
<script src="jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function timedCount(){
$.ajax({
type: 'POST',
url: "check_time.php",
success: function(data){
if (data == "LOGOUT") {
window.location = 'index.php';
}
}
});
setTimeout("timedCount()",10000);
};
</script>
this is the code on the check_time.php
<?php
session_start();
if (isset($_SESSION['last_activity'])){
if(time() - $_SESSION['last_activity'] > 1800){
session_unset();
session_destroy();
echo "LOGOUT";
}
}else{
echo "LOGOUT";
}
?>
I asked this same question last week I wanted to post my latest code so I stated a new question. I really greatly appreciate your help!!!!!
try :
if (jQuery.trim(data) == "LOGOUT")
{
...
}

Categories