I am trying to call a php script which destroys session and reload a page after it.
$(document).bind("active.idleTimer", function(){
$.post("data.php?data=active");
location.reload();
});
data.php
if($_GET['data'] == 'active') {
session_destroy();
}
It does not destroy the session, only if I manually open the url data.php?data=active it does, why is that? Thanks!
The problem is that the script you send the request to is using its own session. So, the user has a session, which is different from the session you send the "refresh idle state" request.
One solution would be to just start a timer using javascript and when that timer runs out, just refresh the page.
That's why it only works when you actually access the data.php page.
If you want to use the data stored in the $_SESSION array, you need to start or resume the existing session using session_start(). In your data.php, try this:
if($_GET['data'] == 'active') {
session_start();
session_destroy();
}
Please, take in consideration that session_start() should be used before you send any output to the client.
Hope it helps!
Modified:
$.post("data.php", {data: active}, function(whatever){}
and in your php file use:
$_POST['data'];
Related
I have a strange problem in my online test management system.
Some users in the test form (test.php) need long time to answer the question and submit the form.
After submitting the form the session is expired and user must login again
this is not a code problem
I set this value in top of all pages
ini_set('session.gc_maxlifetime', 18000);
Is there a way to refresh the session evrey 10 minutes without reloading the page in test form to prevent session expire?
Please help me
Thanks
You can use javascript XHR, or as others call it, AJAX.
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/jQuery.get/
Using ajax you can call a php script that refreshes your session every 10 minutes. :)
This is as far as i can go to "exact".
javascript
var refreshSn = function ()
{
var time = 600000; // 10 mins
setTimeout(
function ()
{
$.ajax({
url: 'refresh_session.php',
cache: false,
complete: function () {refreshSn();}
});
},
time
);
};
// Call in page
refreshSn()
refresh_session.php
<?php
session_start();
// store session data
if (isset($_SESSION['id']))
$_SESSION['id'] = $_SESSION['id']; // or if you have any algo.
?>
Anyway, another solution would be to extend the session time for the test page only using
the solution presented here
How do I expire a PHP session after 30 minutes?
All you need is this (uses jQuery for the $.post):
JavaScript (put this inside your onload-function or something)
setInterval(function(){
$.post('path/to/refresh_session.php');
},600000); //refreshes the session every 10 minutes
refresh_session.php
<?php
session_start();
// if you have more session-vars that are needed for login, also check
// if they are set and refresh them as well
if (isset($_SESSION['token'])) {
$_SESSION['token'] = $_SESSION['token'];
}
?>
The biggest change is in the JavaScript--you don't need a whole function, just one line.
EXTRA INFO
Although I think it's enough to just call session_start() in the php, if I read this right (http://nl3.php.net/function.session-start):
The read callback will retrieve any existing session data (stored in a
special serialized format) and will be unserialized and used to
automatically populate the $_SESSION superglobal when the read
callback returns the saved session data back to PHP session handling.
And during testing I only put the above code on my visitor page, and not on the admin page. But I had both pages open in the same browser (Chrome), and the admin page stayed logged in as well, at least for over an hour (didn't check any longer).
BUT, I don't know if it still works if you only use session_start(), without manually refreshing any session-var at all..
Either way, I like to be sure that the session-vars I need are really still there:)
Javascript:
function doStayAlive() {
var request = new XMLHttpRequest();
request.open('GET', 'stayalive.php', true);
request.send();
}
timerStayAlive = setInterval(doStayAlive, 600000); // 10 minutes
PHP: (stayalive.php)
<?php
session_start();
http_response_code(204);
?>
There is no need to "touch" session variables
I'm having problems with $_SESSION superglobal on AJAX request.
session_start() function is called before any session coding. Session ID is also the same in the calling code and the AJAX response code (tested by echoing session_id() in both scripts). AJAX PHP file is on the same domain. Everything should work as defined by standards, but when I do print_r($_SESSION) in the called AJAX script file I get Arrray( ) output.
I've hit the brick wall... I don't know why is this not working...
Checked both in Chrome and Firefox.
Any ideas?
UPDATE:
The problem is with $.ajax(...) request! When I do AJAX request it knows right session ID, and the session_start() function returns TRUE (successfully continued session) but then it resets my $_SESSSION superglobal! It empties it out... I don't know why yet...
Code:
index.php:
<?php
session_start();
$_SESSION['Test']='O.K.';
echo("SESSION_ID: " . session_id());
echo("SESSION_SIZE:" . sizeof($_SESSION));
?>
... Standard HTML stuff and jQuery include ...
<script>
$.ajax(
{
type: "POST",
url: "AJAXTest.php",
data: null,
success: function(sData) { alert(sData); }
});
</script>
AJAXTest.php:
<?php
session_start();
echo("SESSION_ID: " . session_id());
echo("SESSION_SIZE:" . sizeof($_SESSION));
?>
index.php output:
SESSION_ID: xxxxxxxxxxxxxxxxxxxxxxx
SESSION_SIZE: 1
Alert output:
SESSION_ID: xxxxxxxxxxxxxxxxxxxxxxx (right session id)
SESSION_SIZE: 0
And after the AJAX call $_SESSION is empty. Across all other scripts with the same session... I'm baffled...
it might be because if u didn't put any value in $_SESSION . it will show you array() on doing print_r($_SESSION)
try setting up a value $_SESSION['user']='frankie'
then do print_r($_SESSION);
session_id() is never shown in $_SESSION array.
It might be a problem not with AJAX, but with the session itself. Now you are just testing the $_SESSION array and session id, but not the session storage itself. Try to see if session state keeps the same in several non-AJAX requests. For example, use this:
$_SESSION['Test' . time()]='O.K.';
Instead of this:
$_SESSION['Test']='O.K.';
When refreshing the page, your SESSION_SIZE count should increase. If it does not increase, maybe session storage parameters in php.ini are incorrect? For example, problems while writing sessions to files or issues with memcache if you use that for sessions.
Also be sure that no other requests are made between page and ajax call - maybe some called script resets your $_SESSION array?
The problem was in my custom php.ini file... It obviously screwed up some session important settings (even they were not defined -> changed).
Result was that every call to session_start() would reset $_SESSION superglobal and empty it, but leave the same session ID what confused me and threw in the wrong direction. Until I've stripped down to the bone everything it was clear that error was not in my code.
Thanks everyone who took interest.
I have a login page that sets session variables upon successful login. The login page then redirects to an admin page. The admin page is able to read session variables just fine. But when I do a jQuery load() function that loads viewUsers.php in the content div the session variables are gone. The weird part is the session id is the same.
I used var_dump() on both the admin page and the viewUsers page. The admin pages shows all the proper variables from the login page but the viewUsers page which is called with a jQuery load() function var_dump of $_SESSION is blank. var_dump of $_COOKIE['PHPSESSID'] has the proper ID though, it doesn't make any sense to me.
This is how I set the session variables.
$_SESSION['userID'] = $userInfo['ID'];
$_SESSION['userType'] = $userInfo['userType'];
$_SESSION['programID'] = $userInfo['programID'];
This is the jQuery
$("#content").load("viewUsers.php");
All pages have session_start() at the very top. The session variables also didn't work when I tried window.open and window.location instead of a jQuery load() function.
Some how the session variables are getting lost even though I have the correct session id. If anyone could shed any light on this I would really appreciate it!
As of right now I'm populating hidden fields and using a post function instead of load to get around it. I understand this isn't the best way, but it's the only way I could figure out how to do it.
Edit:
Here is the top of the index which read the session variables fine.
<?php
session_start();
//require("session.php");
if(!isset($_SESSION['userID'])){
header("location: ../login/index.php");
}
?>
Here is the entire viewusers
<?php
session_start();
//foreach($_POST as $name => $value){
//$_SESSION[$name] = $value;
//}
//echo " session id " . $_COOKIE['PHPSESSID'];
var_dump($_COOKIE);
var_dump($_SESSION);
?>
<?php require("adminFunctions.php"); ?>
<h2>View Current Users</h2>
<?php require("userlinks.php"); ?>
<table id="userTable" class="tablesorter">
<?php getUsers($_SESSION['programID'], $_SESSION['userType']) ?>
</table>
<script type="text/javascript">
$('td[name="userID"]').hide();
//$("#userTable th").click(function(){
//color();
//colorTable();
//color();
//});
function colorTable(){
$("tr:odd").css("background-color", "#c0c0c0");
$("tr:even").css("background-color", "#ffffff");
}
function color(){
$("tr:odd").css("background-color", "#ffffff");
$("tr:even").css("background-color", "#ffffff");
}
$(document).ready(function(){
//colorTable();
$("#userTable").tablesorter({widgets: ['zebra']});
});
</script>
Another Edit:
Here is the javascript code to load viewusers
The only reason I'm using post is because I set the session variables as hidden fields in order to pass session variables. On viewusers I use a foreach loop to set the session variables. I understand this isn't secure.
function maintainUsers(){
$.post("viewUsers.php", $("#sessionform").serialize(),function(data){
//alert(data);
$("#content").load("viewUsers.php");
});
}
Might be a long shot but are you using any framework or cms? I know that wordpress would delete session variables (http://blog.ginchen.de/en/2008/08/15/session-variablen-in-wordpress/) can you show the javascript code you're using to load viewUsers? Are you programming on a local server?
If you got correct $_COOKIE['PHPSESSID'], then try to add session_id() assignment before session_start() like this:
<?php
/** Add this: **/
if (isset($_COOKIE['PHPSESSID']))
session_id($_COOKIE['PHPSESSID']);
/** Start session **/
session_start();
/** Rest of the script... **/
if(!isset($_SESSION['userID'])){
header("location: ../login/index.php");
}
?>
I use this all the time and have no problems with sessions in PHP.
You have some spaces before the php open tag. They send output to the browser, and thus, session doesn't get started.
I suspect that the session isn't being started. I've had similar problems in the past all to find out that the session was not started in the first place.
A question: did you try printing out the value in the session variable just to make sure it's there? :
Before calling the page
and after calling the page.
Normally, this sort of error occurs when you dont use session_start() to read the session data.
Try placing (Although, you said you have, I would suggest rechecking)
session_start();
At the beginning of your viewUsers.php
In case, the above is not the case, thenyour current page (the one from which you execute the .load() function) is resetting the session and tampering with the values. Unless you upload the code or find it out, there is no solution for this case.
I would suggest something simple.
Include this in EVERY file.
<?php
session_name("yourapplication_session");
session_start();
?>
For logging out a user from my website, I am redirecting the page to logout.php where I am using session_destroy() function. Even there also, logout functionality is not working without session_start() function. By adding session_start() function before session_destroy() function, I am able to logout the user successfully.
Why do I need to use session_start() function everytime and in every page where I am doing something related to sessions?
session_destroy() destroys the active session. If you do not initialized the session, there will be nothing to be destroyed.
Why do I need to use session_start() function everytime and in every page where I am doing something related to sessions?
So PHP knows which session to destroy. session_start() looks whether a session cookie or ID is present. Only with that information can you destroy it.
In the default configuration, PHP Sessions operate off of the hard disk. PHP asks you to explicitly tell it when you need this support to avoid unnecessary disk IO.
session_start() also tells PHP to find out if the user's session exists.
session_start() creates a session or
resumes the current one based on a
session identifier passed via a GET or
POST request, or passed via a cookie.
as per http://php.net/manual/en/function.session-start.php
Essentially by calling session_start(), PHP reads the header and cross references that session ID to what is on your system(file system/database/etc), which can then populate the $_SESSION that is relavent to that specific user. Which in turn allows you to call session_destroy() because it knows what session to actually destroy.
consider session_start() as your way of telling the php engine.... that you want to work with sessions.
and, as i understand it, always make that to be the first line ever in php page.
I was confused with the usage of session_start(); and every time I was using a session variable, I was calling session_start. Precisely, I had session_start(); more than once on each page (without even calling session_destroy()). For example,
// 1st call
session_start();
if (!isset($_SESSION['UserID']))
{
// Do something
}
else
{
// Do something else
}
// .... some other code
// 2nd call
session_start();
if (!isset($_SESSION['UserID']))
{
// Do something totally different
}
else
{
// Do something else totally different
}
This was creating a performance issue for me. So I ended up calling session_start(); just once at the very top of the page and everything seems to be working fine.
You have to call session_start once (and only once) in every file you want sessions to work in.
A common approach allowing you to only call it once is to have a dispatcher file as your index.php; call session_start in here and have this page include others based on the url's $_GET.
<?php
session_start();
if(isset($_GET['page']) && file_exists('pages/'.$_GET['page'].'.php') {
include $_GET['page'];
}
?>
//www.mysite.com/index.php?page=fish will display /pages/fish.php with session access
having big trouble managing my sessions so I'm asking help.
the scenario
from 1 iphone I load index.php login form here
jquery
$("#login").live('click', function(event) {
//here I've the user input username and password an load the login.php
}
in login.php I also have the session_start() and If user is indeed who he claims to be I declare session['user'] = $user; and session['pass'] = $pass; and then redirect him to imap.php
imap.php has also session_start()
he does everything and returns a html string with some divs I will use as buttons
jquery
$("#erase").live('click', function(event) {
//here i load the erase.php
erase.php
also have session_start(), but now the session['user'] and session['pass'] are gone...
all the loads are made with post method
What can I do to maintain the sessions variables?
Thanks
One very important thing to remember is that session_start() must be called first, before anything in your php script.
example:
..the rest of your code
?>
Also, make sure there is no whitespace between the session_start() and the
It would also be a good idea to check your error log file (assuming you have one). They are very helpful when working with sessions.
Hope this helps!