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";
}
?>
Related
In the header ( header.phtml ) I start the session :
<?php
if (session_status() == PHP_SESSION_NONE)
session_start();
?>
<!DOCTYPE html>
<html>
<head>
...
Now in other page I want to set a session value :
<script type="text/javascript">
$(document).ready(function() {
$("#add_reservS").on("click", function(e) {
<?php
$_SESSION['nb_ajout_client'] = 0;
?>
});
...
Then I increment this session value in other page :
public function ajouterExecAction($src = '', $pk_src = ''){
$client = new Client();
$client->ajouter($_POST);
if ($src == '')
$this->response->redirect('ReferentielClient');
else {
$_SESSION['nb_ajout_client']++;
...
}
...
}
Now inside another page I want to get this session value :
<script type="text/javascript">
$(document).ready(function() {
$("#btn_retour").on("click", function() {
var back = "<?php echo $previous; ?>";
if (back == "list_reserv")
window.history.back();
else {
var nb_back = "<?php echo $_SESSION['nb_ajout_client']; ?>";
alert("session nb ajout client = "+nb_back); // nb_back is blank !
}
});
});
</script>
The alert show a blank value ! So what is wrong in my approach ?
You must start each document with session_start();. While it is no longer required to be the very first line, it does need to be present before you do anything with a session in the file.
It is common to start the session from a common include file which is then included in every page which needs the session. Thus you only need to write it once.
In a.php, i start the session, and i use ajax to post data to b.php.
in b.php, if have session, is find, if no session, do nothing.
but i always to read the session is NULL, i need to check user validity or security reason.
How to solve it?
the return always NULL
a.php
<?php
session_start();
$_SESSION['userid'] = '1123';
$_SESSION['username'] = 'henry';
if($_SESSION['userid']) {
?>
<script>
$("button#Search").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "b.php",
data: {
search: $("input#search").val()
},
success: function(response){
$("#message").html(response);
},
error: function(){
console.log("error");
return e.defaultPrevented || e.returnValue == false;
}
});
});
</script>
<?php } ?>
b.php
<?php
if($_SESSION['userid']) {
echo "success";
} else {
var_dump($_SESSION);
}
?>
You also need to add start session in b.php
session_start();
if($_SESSION['userid']) {
echo "success";
} else {
var_dump($_SESSION);
}
Your b.php file needs to have session_start() as well.
<?php
session_start();
if($_SESSION['userid']) {
echo "success";
} else {
var_dump($_SESSION);
}
?>
I have a multi -part process
step 1:on page.php I evoke a facebook pop-up authentication window with the URI going to page2.php
https://facebook.com/dialog/oauth?client_id=ID&redirect_uri=http://domain.com/page2.php?-Your+Special+Token+1170-&type=user_agent&fbconnect=1&scope=publish_stream
on page2.php I want to process this token by reading it from the url and storing it as a cookie
<?php
session_start();
if ( empty($tkn) ) { ?>
<script>
(function () {
try {
var q = location.href.split('#');
var a = q[1];
var q2 = a.split('=');
var a2 = q2[1];
var q3 = a2.split('&');
var a3 = q3[0];
setTimeout(function () {
top.location.replace('http://domain.com/cookie.php?tkn=' + a3);
}, 200);
} catch (e) {
top.location.replace('http://domain.com/cookie.php?retry=1&tk=broken_' + encodeURI(e.message));
}
})()
</script><? } else {
print $_GET['tkn'];
}
$_SESSION['tkn'] = $tkn;
$tkn = $_POST["tkn"];
if(isset($tkn)) {
setcookie("tkn", $tkn);
echo "success";
}
?>
page.php detects the cookie and echoes out the token $tkn and reloads the page
<?php
session_start();
?>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$.post('page2.php',{tkn: tkn}, function(data){
if(data=='success'){
location.reload(true)
}
});
</script>
<?php echo $tkn; ?>
the problem is I cant get any of this to work. The popup goes into an infinite error loop and nothing is refreshed or echoed.
I have a dynamic login header. 2 links, login / register and profile / logout.
I have a php class function that was being used to check if logged in and displaying relevant links, it worked fine.
I then moved to an ajax login as I didn't want a page refresh and the login box drops down and rolls back up. Again, it works fine.
I've noticed a slight issue, by slight I mean very irritating :)
Once logged in, Every single page refresh on new page shows a flicker where 'profile' becomes 'login' and then flickers back again. It only happens when the page is loading and doesn't last long but it's not very nice.
Could someone help me solve it please? I'm pretty new to Ajax/jQuery and spent ages wiht the help of some guys in here getting the ajax/jquery part functional in the first place.
this is script that toggles the login divs
<script>
window.onload = function(){
$(function() {
var loggedIn = <?php echo json_encode($general->loggedIn()); ?>;
$("#loggedIn").toggle(loggedIn);
$("#loggedOut").toggle(!loggedIn);
});
}
</script>
Thanks
EDIT: Ajax
function validLogin(){
$('#error').hide();
var username = $('#username').val();
var password = $('#password').val();
if(username == ""){
$('input#username').focus();
return false;
}
if(password == ""){
$('input#password').focus();
return false;
}
var params = {username: username, password: password};
var url = "../loginProcessAjax.php";
$("#statusLogin").show();
$.ajax({
type: 'POST',
url: url,
data: params,
dataType: 'json',
beforeSend: function() {
document.getElementById("statusLogin").innerHTML= '<img src="../images/loginLoading.gif" /> checking...' ;
},
success: function(data) {
$("#statusLogin").hide();
if(data.success == true){
$('#loggedIn').show();
$('#loginContent').slideToggle();
$('#loggedOut').hide();
}else{
// alert("data.message... " + data.message);//undefined
$("#error").show().html(data.message);
}
},
error: function( error ) {
console.log(error);
}
});
}
Use PHP to hide the unwanted element by doing the following
<?php
$loggedIn = $general->loggedIn();
?>
... Some HTML
<div>
<div id="loggedIn" <?php echo ( $loggedIn ? '' : 'style="display: none;"' ); ?>>
.... Logged in stuff
</div>
<div id="loggedOut" <?php echo ( !$loggedIn ? '' : 'style="display: none;"' ); ?>>
.... Logged Out Stuff
</div>
</div>
<script>
var loggedIn = <?php echo json_encode($loggedIn); ?>;
$('#loginForm').submit(function() {
... Handle form submit
... When ajax returns true or false we can set loggedIn and then toggle the containers
});
</script>
// CSS-Stylesheet
#loggedIn,
#loggedOut {display: none}
<script>
$(document).ready(function() {
var loggedIn = <?php echo json_encode($general->loggedIn()); ?>;
if (loggedIn == true) { // i can just guess here...
$("#loggedIn").show();
}
else {
$("#loggedOut").show();
}
});
</script>
Three possible solutions:
If the script element is placed inside the body, move
it to head element.
Use the following script instead:
$(document).ready(function () {
'use strict';
var loggedIn = <?php echo json_encode($general->loggedIn()); ?>;
$('#loggedIn').toggle(loggedIn);
$('#loggedOut').toggle(!loggedIn);
});
Hide both links in the "logged in" div using $('#loggedIn
a).hide(); and then, show them on the window.onload event using
$('#loggedIn a).show();. A bit dirty, bit it may work.
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")
{
...
}