read data returned from jquery .post - php

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")
{
...
}

Related

how to delete/destroy/unset a specific php session

I need to delete/destroy/unset a specific session
$('#btnlogout').on('click', function(){
$.post('pro.php', {fn: 'btn_logout'}, function(data){
location.href = location.href;
});
});
pro.php
function btn_logout(){
//$_SESSION['id'] = 5; //this works
unset($_SESSION['id']); // doesn't work
destroy_session(); // doesn't work
}
echo $_SESSION['id'] on main page always gives me a value
here - How do I destroy a specific session variable in PHP? unset($_SESSION['id']) is accepted answer, but I tried so many times - doesn't work
The unset method itself does the trick but until the page is refreshed it echo the last instance. you can try this
session_start();
if(isset(($_SESSION['id'])){
unset($_SESSION['id']);
die();
header ('Location: index.php'); //optional line, any other page can be used
}

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

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.

stop other users to browse to some pages of my website

In my website i have used ajax at many places... But the problem is that the file, lets say some_ajax_file.php, is visible in the source code... I want that other users dont just type this in the url and go to this page... If they do so, they will then be redirected to another page...
I tried following code on that ajax page:
function curPageName() {
return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
}
$cur_page=curPageName();
and checked it
if($cur_page=="some_ajax_file.php")
//then redirect...
it is working if the type some_ajax_file.php in the url...but the problem is that the the ajax function where i used this some_ajax_file.php is not working....plz help me ....i m stuck....
You must have to search for $_SERVER['HTTP_X_REQUESTED_WITH']
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
{
// I'm AJAX!
}
else
{
header();
die();
}
Create a Session at the time of Login
<?php
session_start();
// store session data
$_SESSION['Username']= Userid;
?>
and check the Session Available on that Page...
session_start();
if(empty($_SESSION['Username'])) {
//Redirect them to common page....
}
if the session availed then Show the page
Otherwise redirect them to login page....

Call to a php logout script using jQuery

I want my user to be automatically loged out of the site if there has been no activity for half hour. (Code You see below is set for 70 seconds not 1/2 hour).
I realize that what I need is to use jQuery ... this I am extremly new to ... to load my php script. (I've been working on this for way too long) This is what I have so far.
This is in the head of my page.
var log_me_out = true;
setTimeout(function(){
$.post({
url: "check_time.php",
//data: optional, the data you send with your php-script
success:function(){
if(log_me_out == 'yes'){
window.location = 'index_test.php';
}
}
})
}, 80000);
</script>
This my check_time.php page
<script type="text/javascript">
var log_me_out = true;
</script>
<?php
include('pagetoretrivepassword.inc.php');
session_start();
if($_SESSION['admin_login'] != $password){
session_unset();
session_destroy();
?>
<script type="text/javascript">
log_me_out = 'yes';
</script>
<?php
}else{
?>
<script type="text/javascript">
log_me_out = 'no';
</script>
<?php
}
?>
Well it looks good to me, but I would suggest a bit of a simplification. The best way to do it would be to use the code you have within the setTimeout function, and within it check when the user was last active. So set up a variable like 'lastActive', and using something like:
$(document).click(function(){
var currentTime = new Date();
lastActive = currentTime.getSeconds();
});
Then in your setTimeout function you do something like:
var currentTime = new Date();
if(lastActive + 5000 < currentTime.getSeconds()){
//If user hasn't been active for 5 seconds...
//AJAX call to PHP script
}else {
setTimeout(theSameFunction(),5000);
}
Then in your PHP simply destroy the session, and the success callback function should then simply have:
window.location = 'index_test.php';
To send users on their way.
The javascript you wrote on your php file will not be executed.
To know what your php script do, use that code :
Javascript :
$.post('check_time.php', function(data)
{
if(data == 'yes')
{
window.location = 'index_test.php';
}
});
Php :
session_start();
if($_SESSION['admin_login'] != $password)
{
session_unset();
session_destroy();
echo 'yes';
}
else
{
echo 'no';
}
Your code needs to return something that is parsable such as JSON, XML, or HTML. For example, change your check_time.php to output this:
<?php
include('pagetoretrivepassword.inc.php');
session_start();
header('Content-type: application/json');
if($_SESSION['admin_login'] != $password){
session_unset();
session_destroy();
json_encode(array("log_me_out"=>"true");
}else{
json_encode(array("log_me_out"=>"false");
}
?>
Edit your HTML to include this line of JQuery code:
setTimeout(function(){
$.post("check_time.php", function(d){
if(d.log_me_out){
window.location = 'index_test.php';
}
});
}, 80000);
This problem is solved here is the final working code
code on 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 (jQuery.trim(data) == "LOGOUT") {
window.location = 'LOGOUT.php';
}
}
});
setTimeout("timedCount()",10000);
};
</script>
Here is the code on the check_time.php page
<?php
session_start();
if (isset($_SESSION['last_activity'])){
if(time() - $_SESSION['last_activity'] > 1800){
session_unset();
session_destroy();
echo "LOGOUT";
}
}else{
echo "LOGOUT";
}
?>

Categories