I have set 2 min for session timeout and if it occurred the page
will redirect to a session timeout page.
However, I have some pages that could be browsed without login.
In these pages, if I leave it more than 2 min, pop out will appear asking user to log in again. User will go back to click it and it will redirect to session timeout page.
Could anyone teach me, how to get rid of this such that the pages be browsed without login should not occur session time?
ajax.js
window.onload = init;
var interval;
function init() {
interval = setInterval(trackLogin, 1000);
}
function trackLogin() {
var xmlReq = false;
try {
xmlReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlReq = false;
}
}
if (!xmlReq && typeof XMLHttpRequest != 'undefined') {
xmlReq = new XMLHttpRequest();
}
xmlReq.open('get', 'check.php', true);
xmlReq.setRequestHeader("Connection", "close");
xmlReq.send(null);
xmlReq.onreadystatechange = function() {
if (xmlReq.readyState == 4 && xmlReq.status == 200) {
if (xmlReq.responseText == 1) {
clearInterval(interval);
alert('You have been logged out. You will now be redirected to home page.');
document.location.href = "index.php";
}
}
}
}
firstSession
<?php
// session_start ();
if (! isset ( $_SESSION ["isLoggedIn"] ) || ! ($_SESSION ['isLoggedIn'])) {
// code for authentication comes here
// ASSUME USER IS VALID
$_SESSION ['isLoggedIn'] = true;
$_SESSION ['timeOut'] = 120;
$logged = time ();
$_SESSION ['loggedAt'] = $logged;
// showLoggedIn ();
} else {
require 'timeCheck.php';
$hasSessionExpired = checkIfTimedOut ();
if ($hasSessionExpired) {
session_unset ();
header ( "Location:index.php" );
exit ();
} else {
$_SESSION ['loggedAt'] = time ();
}
}
?>
footer.php
<?php include ('includes/firstSession.php'); ?>
<footer class="main">
<div class="wrapper container">
<div class="copyright">All Rights Reserved
</div>
<div class="logo"><img src="images/logo.png"></div>
</footer>
</div>
draft ajax.js
window.onload = init;
var interval;
function init() {
interval = setInterval(trackLogin, 1000);
}
function trackLogin() {
var xmlReq = false;
try {
xmlReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlReq = false;
}
}
if (!xmlReq && typeof XMLHttpRequest != 'undefined') {
xmlReq = new XMLHttpRequest();
}
xmlReq.open('get', 'check.php', true);
xmlReq.setRequestHeader("Connection", "close");
xmlReq.send(null);
xmlReq.onreadystatechange = function() {
if (xmlReq.readyState == 4 && xmlReq.status == 200) {
return json_encode(array(
'role' => $_SESSION['role'], //assuming something like guest/logged-in
'user_id' => $_SESSION['user_id']
));
var obj = xmlReq.responseText;
var jsonObj = JSON.parse(obj);
//now we can make a comparison against our keys 'role' and 'user_id'
if(jsonObj['role'] == 'guest'){
//guest role, do something here
} else if (jsonObj['role'] == 'logged-in') {
alert('You have been logged out. You will now be redirected to home page.');
document.location.href = "index.php";
//do something else for logged in users
}
I think since you have a session that is persistent whether logged in or not, you need to base your action on the username (however that is set). See if this is what you are trying to do. I have notated for clarity:
myfunctions.php
<?php
// return a session set on not set OR false if set
function is_loggedin()
{
return (!empty($_SESSION["isLoggedIn"]));
}
// Check if username is set (not sure how your usernames are stored in your session
// but that is what you want to check here
function user_set()
{
return (!empty($_SESSION["username"]));
}
// Do your set time function
function set_time_out($timeout = 120)
{
$_SESSION['isLoggedIn'] = true;
$_SESSION['timeOut'] = (is_numeric($timeout))? $timeout : 120;
$_SESSION['loggedAt'] = time();
}
function process_timeout($supRed = false)
{
// If a user has NOT already been poking around your site
if(!is_loggedin()) {
// Set the timeout
set_time_out();
return 0;
}
else {
// If a navigating user is logged in
if(user_set()) {
// Check for expire time
require('timeCheck.php');
// If they have been timed out
if(checkIfTimedOut()) {
if(!$supRed) {
// destroy the session and forward to login (or wherever)
session_destroy();
header("Location:index.php" );
exit();
}
return 1;
}
}
// Set the logged time by default
$_SESSION['loggedAt'] = time();
}
return 0;
}
header.php
<?php
include_once("includes/firstSession.php");
include_once("includes/myfunctions.php");
process_timeout();
?><!DOCTYPE html>
...etc
check.php
<?php
include_once("includes/firstSession.php");
include_once("includes/myfunctions.php");
echo process_timeout(true);
EDIT:
This is the entire script, both js and php.
// return a session set on not set OR false if set
function is_loggedin()
{
return (!empty($_SESSION["isLoggedIn"]));
}
// Check if username is set (not sure how your usernames are stored in your session
// but that is what you want to check here
function user_set()
{
return (!empty($_SESSION["username"]));
}
// Do your set time function
function set_time_out($timeout = 120)
{
$_SESSION['isLoggedIn'] = true;
$_SESSION['timeOut'] = (is_numeric($timeout))? $timeout : 120;
$_SESSION['loggedAt'] = time();
}
function checkIfTimedOut()
{
if(!empty($_SESSION['loggedAt'])) {
$active = ($_SESSION['loggedAt'] + strtotime("120 seconds"));
$now = time();
return (($active - $now) > 0);
}
return true;
}
function process_timeout($supRed = false)
{
// If a user has NOT already been poking around your site
if(!is_loggedin()) {
// Set the timeout
set_time_out();
return 0;
}
else {
// If a navigating user is logged in
if(user_set()) {
// Check for expire time
// If they have been timed out
if(checkIfTimedOut()) {
// destroy the session
session_destroy();
if(!$supRed) {
// Forward to login (or wherever)
header("Location:index.php" );
exit();
}
return 1;
}
}
// Set the logged time by default
$_SESSION['loggedAt'] = time();
}
return 0;
}
check.php:
// Include the functions here
if(!empty($_POST['getPost'])) {
echo json_encode(array("redirect"=>process_timeout(true),"sess"=>$_SESSION));
exit;
}
CALLING PAGE:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
function init()
{
interval = setInterval(trackLogin, 2000);
}
function trackLogin()
{
$.ajax({
url: '/check.php',
data: { getPost: true },
type: 'post',
success: function(response) {
var instr = JSON.parse(response);
console.log(response);
if(instr.redirect == 1) {
clearInterval(interval);
alert('You have been logged out. You will now be redirected to home page.');
document.location.href = "index.php";
}
}
});
}
$(document).ready(function() {
var interval;
init();
});
</script>
EDITED
Related
my english is not good. sorry.
I want developing a CMS with php. And I want to change the on_desk database column to 1 when the post edit page is opened and the on_desk column to be 0 when exiting same page
By doing this while you are in the Edit Post window tab. I want to prevent the same page from opening in a new window.
I used the following solution. But sometimes it doesn't work well.
For example, when I cancel the dialog, it does not work well
Do you have another solution? For example, the way not to use beforeunload.
Javascript|jQuery:
function clearDesk(){
$.post('clearOnDesk.php',{
"id":parseInt($('body').attr('data-pageId')),
}, function(){
$('body').attr('data-desk',1)
});
}
function setDesk(){
$.post('setOnDesk.php',{
"id":parseInt($('body').attr('data-pageId')),
}, function(){
$('body').attr('data-desk',2)
});
}
setDesk();
const beforLoadFunc = function beforLoadFunc () {
clearDesk();
if(parseInt($('body').attr('data-desk')) == 1){
setTimeout(() => {
window.addEventListener('mousemove', (e) => {
setDesk();
});
}, 1000);
}
}
window.addEventListener('beforeunload', function onBeforeUnload(e) {
setTimeout(beforLoadFunc, 500);
const dialogText = 'are you sure?';
e.returnValue = dialogText;
return dialogText;
});
clearOnDesk.php
if($_POST)
{
$id = (int)$this->post('id');
if($id && $id != '')
{
$w['id'] = $id;
} else die("die!");
$d['on_desk'] = 1;
$this->db->update('post',$d,$w,["i","i"]);
//update on_desk to 0 for (post row) in database by (pageId).
//by PHP Prepared Statements
}
setOnDesk.php
if($_POST)
{
$id = (int)$this->post('id');
if($id && $id != '')
{
$w['id'] = $id;
} else die("die!");
$d['on_desk'] = 2;
$this->db->update('post',$d,$w,["i","i"]);
// update on_desk to 1 for (poster row) in database by (pageId).
//by PHP Prepared Statements
}
I have the following downloadZip.html. The download works in Chrome and Edge, but not in IE. This file gets called as below from jspf page. When I click "Download listed documents" it call popupDownloadWindow(), which will open downloadZip.html in plainview. This html when loaded calls enableLink() and the flow goes. As the view is plainview, only first if block of enableLink() is executed (if(callerview == "plainview")). Not sure if this is happening because of setTimeout(). Please help me here. Let me know for any information.
function checkReturn(){
//alert('checkReturn - sessionsNotOk global var = '+sessionsNotOk);
if (sessionsNotOk != "DEF") {
var docbases = sessionsNotOk.split(",");
//alert('checkReturn - docbases arr = '+docbases+', length='+docbases.length);
if (docbases.length == 1 && docbases[0] == "OK"){
// All sessions are faja
document.getElementById('divIndicator').style.display='none';
document.getElementById('checkSession').style.display='none';
document.getElementById('noSession').style.display='none';
document.getElementById('dlink').style.display='inline';
document.getElementById('dlink').style.textAlign='center';
document.getElementById('dlink').style.display='';
} else {
// We need to show the sublogin dialog
var nextDocbase = docbases[0];
//alert("Next NOT AVAILABLE session = "+nextDocbase);
window.opener.$('#subloginmessage').css('display','none');
window.opener.$('#loginIndicator').css('display','none');
window.opener.$('#sub-uid').val(window.opener.$('#user_name').text());
window.opener.$('#sub-uid').attr('disabled','disabled');
window.opener.$('#sub_docbase').text(nextDocbase);
document.getElementById('checkSession').style.display='none';
document.getElementById('noSession').style.display='inline';
document.getElementById('noSession').style.textAlign='center';
document.getElementById('noSession').style.display='';
window.opener.sublogin_fw = "download";
window.opener.sublogin_db = nextDocbase;
window.opener.$('#sublogindialog').dialog('open');
window.opener.$('#sublogindialog').dialog('option','title','Login to docbase: ' + nextDocbase + ' and click on Download listed documents link again!');
}
return;
}
//Check again in 0.5 second
setTimeout("checkReturn()",500);
//setTimeout(function() {
// checkReturn();
//}, 500);
}
Complete code:
<script>
var downloadZipChildWindow;
function popupDownloadWindow(){
downloadZipChildWindow = window.open('../html/downloadZip.html?view=plainview','downloadwindow','width=300,height=200,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,copyhistory=no,resizable=no');
}
</script>
<a id='download_link' class='download_link' href="#" onClick="popupDownloadWindow()">Download listed documents</a>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Download documents as Zip file</title>
<script type="text/javascript" src="../js/jquery-1.6.1.min.js" ></script>
<style type="text/css">
p
{
font-family:"Verdana";
font-size:small;
}
a
{
font-family:"Helvetica";
font-size:small;
}
</style>
<script type="text/javascript">
var lastParam;
var sessionsNotOk = "DEF";
var callerView;
function getParam( paramName )
{
paramName = paramName.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+paramName+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
/*
* Checks the return from ajax servlet call "../downloadzip?ask=isSRPsessionsOK&packageIDs="+pIDs".
* Called always right after checkDocbaseSessions() call.
*/
function checkReturn(){
//alert('checkReturn - sessionsNotOk global var = '+sessionsNotOk);
if (sessionsNotOk != "DEF") {
var docbases = sessionsNotOk.split(",");
//alert('checkReturn - docbases arr = '+docbases+', length='+docbases.length);
if (docbases.length == 1 && docbases[0] == "OK"){
// All sessions are faja
document.getElementById('divIndicator').style.display='none';
document.getElementById('checkSession').style.display='none';
document.getElementById('noSession').style.display='none';
document.getElementById('dlink').style.display='inline';
document.getElementById('dlink').style.textAlign='center';
document.getElementById('dlink').style.display='';
} else {
// We need to show the sublogin dialog
var nextDocbase = docbases[0];
//alert("Next NOT AVAILABLE session = "+nextDocbase);
window.opener.$('#subloginmessage').css('display','none');
window.opener.$('#loginIndicator').css('display','none');
window.opener.$('#sub-uid').val(window.opener.$('#user_name').text());
window.opener.$('#sub-uid').attr('disabled','disabled');
window.opener.$('#sub_docbase').text(nextDocbase);
document.getElementById('checkSession').style.display='none';
document.getElementById('noSession').style.display='inline';
document.getElementById('noSession').style.textAlign='center';
document.getElementById('noSession').style.display='';
window.opener.sublogin_fw = "download";
window.opener.sublogin_db = nextDocbase;
window.opener.$('#sublogindialog').dialog('open');
window.opener.$('#sublogindialog').dialog('option','title','Login to docbase: ' + nextDocbase + ' and click on Download listed documents link again!');
}
return;
}
//Check again in 0.5 second
//setTimeout("checkReturn()",500);
setTimeout(function() {
checkReturn();
}, 500);
}
function enableLink(){
callerView = getParam("view");
var pkgType = "";
var params = "";
var packageIDs = "";
if (callerView == "plainview") {
pkgType = window.opener.$('#hiddenPkgType').attr('value');
// Check available sessions
if (pkgType == 'srp'){
document.getElementById('dlink').style.display='none';
document.getElementById('checkSession').style.display='inline';
document.getElementById('checkSession').style.textAlign='center';
document.getElementById('checkSession').style.display='';
packageIDs = window.opener.$('#hiddenSRPIDs').attr('value');
checkDocbaseSessions(packageIDs);
checkReturn();
}
params = window.opener.$('#hiddenDownloadParams').attr('value');
} else if (callerView == "packagedetailview") {
pkgType = window.opener.$('#hiddenPkgType_DetailedPackageView').attr('value');
if (pkgType == "" || pkgType == null) {
alert("Still loading data, window will be closed. Please click on download button after all data have been loaded on the page!");
window.close();
}
params = window.opener.$('#hiddenDownloadParams_DetailedPackageView').attr('value');
} else if (callerView == "SRP_packagedetailview") {
// Prepare/check remote sessions
packageIDs = window.opener.$('#SRP_DPV_pkgIDs').attr('value');
checkDocbaseSessions(packageIDs);
checkReturn();
pkgType = 'srp';
if (pkgType == "" || pkgType == null) {
alert("Still loading data, window will be closed. Please click on download button after all data have been loaded on the page!");
window.close();
}
params = window.opener.$('#hiddenDownloadParams_SRP_DetailedPackageView').attr('value');
} else if (callerView == "SRP_checkstatusview") {
// Prepare/check remote sessions
packageIDs = window.opener.$('#SRP_CSV_pkgIDs').attr('value');
checkDocbaseSessions(packageIDs);
checkReturn();
pkgType = 'srp';
if (pkgType == "" || pkgType == null) {
alert("Still loading data, window will be closed. Please click on download button after all data have been loaded on the page!");
window.close();
}
params = window.opener.$('#hiddenDownloadParams_SRP_CheckStatusView').attr('value');
}
if (pkgType == 'nlp' || pkgType == 'monnlp') {
document.getElementById('download_zip_stdfilenames_nlp_country').style.display='inline';
document.getElementById('download_zip_stdfilenames_nlp_product').style.display='inline';
document.getElementById('download_zip_stdfilenames_nlp_country').style.textAlign='center';
document.getElementById('download_zip_stdfilenames_nlp_product').style.textAlign='center';
document.getElementById('download_zip_stdfilenames').style.display='none';
} else if (pkgType == 'clp') {
document.getElementById('download_zip_stdfilenames_nlp_country').style.display='none';
document.getElementById('download_zip_stdfilenames_nlp_product').style.display='none';
document.getElementById('download_zip_stdfilenames').style.display='inline';
document.getElementById('download_zip_stdfilenames').style.textAlign='center';
} else if (pkgType == 'ipl') {
document.getElementById('download_zip_stdfilenames_nlp_country').style.display='none';
document.getElementById('download_zip_stdfilenames_nlp_product').style.display='none';
document.getElementById('download_zip_stdfilenames').style.display='inline';
document.getElementById('download_zip_stdfilenames').style.textAlign='center';
}
//Defined as global
zipParamsImp = params + "&filename=import";
zipParamsStd = params + "&filename=standard";
}
function showIndicator(param){
document.getElementById('divIndicator').style.display='inline';
document.getElementById('divIndicator').style.textAlign='center';
document.getElementById('divIndicator').style.display='';
document.getElementById('dlink').style.display='none';
var parameters = "";
if (param == 'import'){
parameters = zipParamsImp;
} else if (param == 'standard') {
parameters = zipParamsStd;
} else if (param == 'standard_nlp_country') {
parameters = zipParamsStd + "_nlp_country";
} else if (param == 'standard_nlp_product') {
parameters = zipParamsStd + "_nlp_product";
}
lastParam = param;
postwith("../downloadzip",parameters);
}
function postwith (to, params) {
var myForm = window.opener.document.createElement("form");
myForm.method="post" ;
myForm.action = to ;
myForm.style.display = 'none';
jQuery.each(params.split('&'), function(){
var pair = this.split('=');
var myInput = window.opener.document.createElement("input") ;
myInput.setAttribute("name", pair[0]) ;
myInput.setAttribute("value", pair[1]);
myForm.appendChild(myInput);
});
var lastInput = window.opener.document.createElement("input") ;
lastInput.setAttribute("name", "download_token_value_id") ;
lastInput.setAttribute("value", "");
myForm.appendChild(lastInput);
window.opener.document.body.appendChild(myForm) ;
myForm.submit();
window.opener.document.body.removeChild(myForm) ;
//setTimeout("checkProgress()",1000);
setTimeout(function(){
checkProgress();
},1000);
}
/*
* Checks return from servlet call "../downloadzip?ask=isready" -> ask whether DownloadAsZipServlet
* has finished its work or not. If finished, close this popup.
*/
function checkProgress(){
window.focus();
$.ajax({
type: "GET",
url: "../downloadzip?ask=isready",
dataType: "text",
//dataType: "script",
//timeout: 2000,
success: function(results)
{
// Normal flow
//var result = eval('('+results+')');
var currParams = window.opener.$('#hiddenDownloadParams').attr('value');
//After closing DPV and clicking on Download Listed Documents button, we have to remove caller param, because there is no caller.
//Caller exists only if openPackage function called, and Download is on a DPV page.
//If we do not remove caller param, then exception occurs.
var callerPrefix = currParams.substring(0,currParams.indexOf('&'));
if (callerPrefix.indexOf('caller=') > -1) {
window.opener.$('#hiddenDownloadParams').attr('value',currParams.replace(callerPrefix+'&',""));
} else {
// No caller param found
}
if (results.indexOf('window.close()') > -1) {
window.close();
}
},
error: function(XMLHttpRequest, textStatus, errorThrown){
window.top.document.location.href = "../jsp/logout.jsp?msg=Application error (HTTPREQ quicksearch download documents). You have been logged out!";
}
});
}
/*
* In case of SRP - checks whether sessions for all required docbases are available.
* It is needed, because SRP package documents can be located in different docbases.
*/
function checkDocbaseSessions(pIDs){
sessionsNotOk = "DEF";
$.ajax({
type: "GET",
url: "../downloadzip?ask=isSRPsessionsOK&packageIDs="+pIDs,
dataType: "text",
success: function(results)
{
//alert(results);
if ($.trim(results) == 'OK'){
//alert("Sessions are OK!");
sessionsNotOk="OK";
} else {
sessionsNotOk=results;
//alert("Sessions are NOT OK! - "+sessionsNotOk);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown){
window.top.document.location.href = "../jsp/logout.jsp?msg=Application error (HTTPREQ quicksearch download documents). You have been logged out!";
}
});
}
</script>
</head>
<body style="background-color: #ffffff; font-family: Verdana, Helvetica; font-size: x-small;" onload="enableLink();">
<div id="divIndicator" style="display: none"><br />
<p>Zip file creation in progress. This may take a few minutes, please wait and do not navigate away or start another query!</p>
<br />
<br />
<span id="qIndicator"> <img border="0" src="../img/indicator.gif"></span>
<br />
<br />
</div>
<p style="text-align: center">Download listed documents</p>
<div id="dlink" style="text-align: center">
With import file names
<br />
With standard file names
With standard file names starting with country
With standard file names starting with product
</div>
<div id="noSession" style="display: none">
<p>Some required sessions are unavailable. Please login to the docbase!</p>
</div>
<div id="checkSession" style="display: none">
<p>Checking required sessions in progress. Please wait...</p>
<br />
<span id="qIndicator"> <img border="0" src="../img/indicator.gif"></span>
<br />
</div>
</body>
</html>
I am creating a login form which if the user tries 3 input login it will automatically block. but the problem is after 1 login only it already block. and All the users have been blocked. I want only after 3 times the username that i input will be blocked. Can someone help me?Thank you.
here is my code...
<!DOCTYPE html>
<?php
function p(){
$xmldoc=new DOMDocument();
$xmldoc->load('person.xml');
$root=$xmldoc->documentElement;
$data=$root->getElementsByTagName('user');
$status="Blocked";
if($data){
$domelemupdate=[];
foreach ($data as $domElement) {
$domElement->childNodes->item(5)->textContent=$status;
}
}
foreach ($domelemupdate as $domElement) {
# code...
$domElement->parentNode->replaceChild($domElement);
}
$xmldoc->save('person.xml');
}
?>
<html>
<head>
<body>
</body>
</head>
</html>
var ctr=0;
window.login = function(e)
{
if (document.frmlogin.login_username.value == "")
{
alert("User name is not blank");
return;
}
else if(document.frmlogin.login_pass.value == "")
{
alert("Password is not blank");
return;
}
else
{
var xmlDoc;
var x;
var txt = "";
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else { // IE 5/6
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.overrideMimeType('text/xml');
xhttp.open("GET", "person.xml", false);
xhttp.send(null);
xmlDoc = xhttp.responseXML;
var ktra=false;
var xml=xmlDoc.childNodes[0];
var name = xml.childNodes["username"];
var pass=xml.childNodes["password"];
var status=xml.childNodes["status"];
for(var i=0;i<xml.childNodes.length;i++){
if(xml.childNodes[i].nodeName=="user"){
name = xml.childNodes[i].childNodes[3];
pass = xml.childNodes[i].childNodes[5];
status = xml.childNodes[i].childNodes[7];
position = xml.childNodes[i].childNodes[9];
if(name.textContent==frmlogin.login_username.value && pass.textContent==frmlogin.login_pass.value && status.textContent== "Active")
{
alert("Login Success!");
}
}
if(ktra==false)
{
ctr+=1
alert("Login Failed !!!" +ctr);
if(ctr==3){
//alert("You are now Blocked!!!" );
x=p()
alert(x);
}
}
}
}
</script>
Whenever i call the function in my ctr==3 .If i run the program,if for example i try first login wrong username . after i click login the text easily update to block,.i want my counter 3 times before it will be block and i want the user that i input will be blocked only not all the users
You should be keeping track of the failed count either in a database, or write to the XML file an incremental count each time they fail to login with valid credentials..
What I am trying to do is increment the value inside the COOKIE in every redirect... but every time I check if the cookie exists it doesn't.
I try to do it with a SESSION also, but the session_id changes in each redirect (I am guessing that the redirect create a new session for some reason )
This is my code
<script language="javascript">
var popexurl = "<?php echo $PopExitUrl ?>";
if(popexurl != ""){
(function() {
setTimeout(function() {
<?php
if (isset($_COOKIE["count"]))
{
//cheak user refreshes
$cookie = (int)++$_COOKIE['count'];
setcookie("count", $cookie, time()+3600);
}
else
{
setcookie("count", 1, time()+3600);
$cookie=0;
}
?>
var __redirect_to = '<?php echo $PopExitUrl; ?>';//
var _tags = ['button', 'input', 'a'], _els, _i, _i2;
for(_i in _tags) {
_els = document.getElementsByTagName(_tags[_i]);
for(_i2 in _els) {
if((_tags[_i] == 'input' && _els[_i2].type != 'button' && _els[_i2].type != 'submit' && _els[_i2].type != 'image') || _els[_i2].target == '_blank') continue;
_els[_i2].onclick = function() {window.onbeforeunload = function(){};}
}
}
window.onbeforeunload = function() {
window.scrollTo(0,0);
document.getElementById('ExitBackDiv').style.display = 'block';
document.getElementById('ExitDiv').style.display = 'block';
setTimeout(function() {
window.onbeforeunload = function() {};
setTimeout(function()
{
window.location = __redirect_to;
}, 500);
},5);
<?php
if ($PopupMessage == ""){
$PopupMessage= "\\n**********************\\nWAIT! WAIT! WAIT! WAIT!\\n\\n**********************\\n\\nDont Miss This LAST CHANCE to become Financially Secure and CHANGE YOUR Lifestyle!!!\\n\\n...Click STAY ON THIS PAGE to activate your LIMITED time offer!";}
?>
var popmsg = "<?php echo $PopupMessage ?>";
if (navigator.userAgent.indexOf("Firefox")!=-1)
{
//setTimeout('window.location="'+__redirect_to+'"', 10);
window.alert(popmsg);
return popmsg;
}
else
{
return popmsg;
}
}
}, 500);
})();
}
</script>
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.
PHP: session_start()
After logged in I am trying to return if the user is either not a fan of a Facebook page, but the result is always "undefined". But if I replace "return" to "alert" works perfectly.
function pageFan()
{
FB.api({ method: 'pages.isFan', page_id: '175625039138809' }, function(response) {
showAlert(response);
});
}
function showAlert(response)
{
if (response == true) {
return 'like the Application.';
} else {
return "doesn't like the Application.";
}
}
var like = pageFan();
document.getElementById('debug').innerHTML = like; //return undefined
This question has already been answered.
Relevant Javascript:
$(document).ready(function(){
FB.login(function(response) {
if (response.session) {
var user_id = response.session.uid;
var page_id = "40796308305"; //coca cola
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
var the_query = FB.Data.query(fql_query);
the_query.wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
$("#container_like").show();
//here you could also do some ajax and get the content for a "liker" instead of simply showing a hidden div in the page.
} else {
$("#container_notlike").show();
//and here you could get the content for a non liker in ajax...
}
});
} else {
// user is not logged in
}
});
That's because the return in showAlert is not returning "into" the pageFan function. The showAlert function is passed as a callback, meaning it will be called later, outside of pageFan's execution. I think you need to read more about callback functions and asynchronous programming.
function showAlert(response)
{
if (response == true) {
document.getElementById('debug').innerHTML = 'like the Application.';
} else {
document.getElementById('debug').innerHTML = "doesn't like the Application.";
}
}