How can I session destroy when user close the page? - php

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

Related

AJAX inserting content instead of redirecting to lock page

I have an if statement that checks if user time logged in is more than 10 seconds, it should redirect the page. it does so without AJAX but it only runs the script after the page is reloaded.
if ($_SERVER['REQUEST_URI'] == '/account/Dashboard' || '/account/Dashboard/?Login=Success')
{
$time = time();
$uid = $userRow['user_id'];
//$auth_user->auto_timeout($time,$uid);
?>
<div id="auto-lock"></div><?php
}
Then I have this js script to run auto-lock.php
<script>
var refresh = setInterval(
(function () {
$("#auto-lock").load("../../inc/ajax_content/auto-lock.php");
}), 10000);
</script>
auto-lock.php
if ($time - $userRow['auto_timeout'] >= 10)
{
$auth_user->redirect("../../account/LockScreen/?Lock=true");
}
Now instead of it redirecting to the Lock screen it simply includes the lock screen within the /account/Dashboard page:
^^^^^ With Ajax Refresh loads into Dashboard instead of redirecting to /LockScreen
Am I perhaps doing something wrong ?
Here you are using
<script>
var refresh = setInterval(
(function () {
$("#auto-lock").load("../../inc/ajax_content/auto-lock.php");
}), 10000);
</script>
load will fetch the data from auto-lock.php and load the html into div #auto-lock. To redirect you need to use this script
<script>
var refresh = setInterval(
(function () {
window.location.replace("../../account/LockScreen/?Lock=true");
}), 10000);
</script>
It will redirect user to auto-lock.php page.Just saw your full code there is no need of auto-lock.php file if you want to lock screen after 10 seconds only js will do the job.

Pass variable with jquery, open php page and pick it up

I have two pages. On page one, called test1.html, I try to retreive the users timezone. I would like to send it of to a php page called test2.php and load that page instead of test1 with the variable (timezone). This is the code.
Test1.html:
<script type="text/javascript">
$(document).ready(function() {
var tz = jstz.determine(); // Determines the time zone of the browser client
var timezone = tz.name(); //'Asia/Kolhata' for Indian Time.
$.ajax({
type: 'POST',
url: 'test2.php',
data: {'timezone': timezone},
cache: false,
success: function(){
setTimeout(function () {
window.location = 'test2.php';
}, 3000);//this will redirct to somefile.php after 3 seconds
}
});
});
</script>
Test2.php
<?php
if(isset($_POST['timezone']))
{
$tz = $_POST['timezone'];
echo "Timezone is " .$tz;
}
else {
echo "Fail!";
}
?>
On pageload of test2.php, I only ever get the 'Fail!' message. The jquery and php part do work correct as I tested it with an alert call in test1.html to log the reponse from the php page. It gave the response I expected.
I think I lose my variable when the code is executed to reload test2.php in the same window. I just don't know how to bypass this problem. I want to use POST rather then GET if possible.
Any help greatly appreciated.
Little note: Idealy I want to use this javascript and the php to be on the same page but the 'problem' there is that php is of course executed serverside first and then it runs je js client side afterwards...
An alternative solution that still allows you to use POST, which you said you'd like, is to store the information in a session variable. The session is an object that can be used to store values between requests. See http://php.net/manual/en/book.session.php
Test1.html:
<script type="text/javascript">
$(document).ready(function() {
var tz = jstz.determine(); // Determines the time zone of the browser client
var timezone = tz.name(); //'Asia/Kolhata' for Indian Time.
$.ajax({
type: 'POST',
url: 'test2.php',
data: {'timezone': timezone},
cache: false,
success: function(){
setTimeout(function () {
window.location = 'test3.php';
}, 3000); }
});
});
</script>
Test2.php
<?php
// Start your session (if not already started)
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Store posted timezone in the session, which will be available in future calls
if(isset($_POST['timezone'])) {
$_SESSION['timezone'] = $_POST['timezone'];
}
else {
echo "Fail!";
}
?>
Test3.php
<?php
// Start your session (if not already started)
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if(isset($_SESSION['timezone']) {
echo "Your timezone is " . $_SESSION['timezone'];
} else {
echo "Fail!";
}
You are misunderstanding the flow of how your client and server are interacting with each other. Your code sends a POST request to test2.php, and THEN (in the success callback that triggers when your request is done) it redirects to test2.php. The first time test2.php is run, it gets the timezone POST variable, but the second time it doesn't. You can see this by looking at network traffic in your browser's developer tools - you'll see two requests to test2.php. The first will return "Timezone is...", and the second (which your browser is showing) says "Fail!"
There are different ways to get what you want, but the easiest would be to skip the AJAX altogether and just send the timezone along with the redirect:
$(document).ready(function() {
var tz = jstz.determine(); // Determines the time zone of the browser client
var timezone = tz.name(); //'Asia/Kolhata' for Indian Time.
// This redirects to test2.php while setting a GET parameter called "timezone"
window.location = 'test2.php?timezone='+encodeURIComponent(timezone);
});
<?php
if(isset($_GET['timezone']))
{
$tz = $_GET['timezone'];
echo "Timezone is " .$tz;
}
else {
echo "Fail!";
}
?>

Destroying session 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.

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

Categories