php session_id change on header redirect - javascript

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()

Related

I want to do something when the beforeunload is canceled

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
}

How to execute code from php file when ajax called

Okay so i have php code which is supposed to check if there is an existing user in database when login is attempted and send back to javascript fail or success
Php code:
<?php
require_once 'Korisnik.php';
require_once 'dbconn/korisnikdb.php';
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// collect value of input field
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$korisnik = getKorisnikByUserPass($username, $password);
if ($korisnik == null) {
$statusArray = array("status"=>"fail");
echo json_encode($statusArray);
return;
} else {
session_start();
$_SESSION["prijavljeniKorisnik"] = $username;
$statusArray = array("status"=>"success");
echo json_encode($statusArray);
return;
}
}
?>
Here i have my javascript code :
$(document).ready(function() {
var usernameInput = $('#usernameInput');
var passwordInput = $('#passwordInput');
var pogresniPodaci = $('#pogresniPodaci');
var praznaPolja = $('#praznaPolja');
pogresniPodaci.hide();
praznaPolja.hide();
$('#submitButton').on('click', function(event) {
var username = usernameInput.val();
var password = passwordInput.val();
console.log(username);
console.log(password);
if (username == '' || password == '') {
praznaPolja.show();
event.preventDefault();
return false;
}
var params = {
'username': username,
'password': password
}
$.post('loginCheck.php', params, function(data) {
console.log(data.status);
if (data.status == 'fail') {
pogresniPodaci.show();
usernameInput.val('');
passwordInput.val('');
return;
}
if (data.status == 'success') {
location.href = 'pocetna';
}
});
event.preventDefault();
return false;
});
});
http://prntscr.com/skb37r -> here you can see status after i press that button
The problem is that php code in loginCheck.php never actually executes, I tried adding echo at start of php file but it doesn't execute.
You are sending http request to localhost. Even if file doesn't exist, your localhost will return status 200, unless it's configured to throw an error.
Try this:
go to http://localhost/loginCheck.php and echo anything there.
echo "This is loginCheck";
If it echoes, you are on the right route to loginCheck file.
If it works, go to browser dev tools > network > and see request headers and find "Request URL" header. it should be "http://localhost/loginCheck.php" - the route to file you visited previously. if its not, you have to fix it in $.post request.

How to avoid the session timeout in non-login situation php?

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

Javascript settimeout doesn't close the popup

Hi guys I'm using this function to open a popup and close it after 3 seconds. The popup opens successfully, but, the settimeout function doesn't works and eventually doesn't close the opened popup.
What am I doing wrong here?
<script type="text/javascript">
function popUp(id,entry,escape)
{
popupWindow = window.open('process_concur.php?id='+id+'&entry='+entry+'&escape='+escape,'Concur','resizable=yes,scrollbars=yes,width=250,height=250');
popupWindow.focus();
setTimeout(function () { popupWindow.close();}, 3000);
}
//reload the current window when the popup is closed.
function popUpClosed() {
window.location.reload();
}
</script>
The popup page which opens (Code)
<?php
include 'classes/class.user.php';
$userMain = new user();
//get parameters
$id = isset($_GET['id']) ? $_GET['id'] : '';
$entry = isset($_GET['entry']) ? $_GET['entry'] : '';
$escape = isset($_GET['escape']) ? $_GET['escape'] : '';
//now, $escape is sha1 and $entry is base64 encoded..decode entry and check if sha1 of decoded entry matches escape
$dentry = base64_decode($entry);
if(sha1($dentry)==$escape)
{
//process concur
if($userMain->reviewExists($id))
{
if($userMain->increaseConcur($id))
{
echo "Done";
exit();
}
}
else
{
//review doesnt no exist
echo "Some problems occured at id doesn't exist";
}
}
else
{
echo "Some problems occured dentry";
}
?>
<script>
window.onunload = function() {
if (window.opener && !window.opener.closed) {
window.opener.popUpClosed();
}
};
</script>
Your code looks correct. Ensure nothing else is interfering with the process.
Also, the popUpClosed() function should be invoked after the window is sent the close signal.
<script type="text/javascript">
function popUp(id,entry,escape)
{
var popupWindow = window.open('process_concur.php?id='+id+'&entry='+entry+'&escape='+escape,'Concur','resizable=yes,scrollbars=yes,width=250,height=250');
popupWindow.focus();
setTimeout(function () { popupWindow.close(); popUpClosed();}, 3000);
}
//reload the current window when the popup is closed.
function popUpClosed() {
window.location.reload();
}
popUp();
</script>

Else condition won't run

I know the title is very annoying but anyways I start my question. I have created a function in a class that's kinda a multi-purpose one. I gave it a parameter which is of boolean type and of course only accepts "true" and "false" as values. Next, I am calling out that function through another PHP file on which the data is posted through ajax and that ajax is called through a button on my HTML page. Let me demonstrate it as a diagram:
I hope you've understood my program flow, now let's come to the code or in other words here is what I've tried:
HTML Page's button:
document.write('<span class="pull-right" style="margin-top: -30px; margin-right: 20px;"><button id="accept_offer" class="btn btn-success" onclick="setPostOfferAcceptance(32);">Accept Offer</button></span>');
AJAX Page:
<?php
require_once '../../Classes/MyClass.php';
$offer_id = $_POST["id"];
$acceptance = $_POST["acceptance"];
$accepted = MyClass::SetOfferAcceptance($offer_id, $acceptance);
if($accepted) $data["status"] = "success";
else $data["status"] = "error";
echo json_encode($data);
?>
MyClass's Function:
public static function SetOfferAcceptance($offerId, $acceptance) {
if(Utilities::IsValid($offerId) && Utilities::IsValid($acceptance)) {
Database::OpenConnection();
$offerId = Utilities::SafeString(Database::$databaseConnection, $offerId);
$acceptance = Utilities::SafeString(Database::$databaseConnection, $acceptance);
$query = "";
if($acceptance == true) {
$query = Database::$databaseConnection->prepare("UPDATE post_offer SET Accepted=1 WHERE Offer_ID = ?");
} else {
$query = Database::$databaseConnection->prepare("UPDATE post_offer SET Accepted=0 WHERE Offer_ID = ?");
}
$query->bind_param("i", $offerId);
$result = $query->execute();
Database::CloseConnection();
if($result) return 1; else return -1;
}
}
And sorry, but finally, here's my javascript function that posts the data to the AJAX page:
function setPostOfferAcceptance(offer_id) {
if($("#accept_offer").text() == "Accept Offer") {
$.post("admin/post_offer/set_post_offer_acceptance.php", {id: offer_id, acceptance: true}, function(data){
if(data.status == "success") {
$("#acceptedOfferModal").modal("show");
setTimeout(function(){ $("#acceptedOfferModal").modal("hide"); }, 2500);
$("#accept_offer").text("Unaccept Offer");
console.log(data.status);
}
}, 'json');
} else if($("#accept_offer").text() == "Unaccept Offer") {
$.post("admin/post_offer/set_post_offer_acceptance.php", {id: offer_id, acceptance: false}, function(data){
if(data.status == "success") {
$("#unacceptedOfferModal").modal("show");
setTimeout(function(){ $("#unacceptedOfferModal").modal("hide"); }, 2500);
$("#accept_offer").text("Accept Offer");
console.log(data.status);
}
}, 'json');
}
}
EDIT: I forgot to post the JS code. But I've updated it now. Please consider it. Thanks.
The problem is that the function SetOfferAcceptance() is never running the else condition which is that if $acceptance is not equal to true.
Why? Can anyone please point out my mistake.
Thanks.
If acceptance is boolean then use the following if...else, i.e. with tripple equals $acceptance === true:
// In AJAX page
if ($acceptance === true) {
$query = Database::$databaseConnection->prepare("UPDATE post_offer SET Accepted=1 WHERE Offer_ID = ?");
} else {
$query = Database::$databaseConnection->prepare("UPDATE post_offer SET Accepted=0 WHERE Offer_ID = ?");
}
Please reference: "How do the equality (== double equals) and identity (=== triple equals) comparison operators differ?"
Update:
Either check for $acceptance value in SetOfferAcceptace, or pass in boolean value to SetOfferAcceptance. Example with latter:
$offer_id = $_POST["id"];
$acceptance = false;
if (isset($_POST["acceptance"]) && $_POST["acceptance"] == 'accepted') {
$acceptance = true;
}
$accepted = MyClass::SetOfferAcceptance($offer_id, $acceptance);
Thanks you all for your answers but I figured out another alternative. That was instead of making $acceptance a boolean I made it a string and converted my JS code into:
function setPostOfferAcceptance(offer_id) {
if($("#accept_offer").text() == "Accept Offer") {
$.post("admin/post_offer/set_post_offer_acceptance.php", {id: offer_id, acceptance: "accepted"}, function(data){
if(data.status == "success") {
$("#acceptedOfferModal").modal("show");
setTimeout(function(){ $("#acceptedOfferModal").modal("hide"); }, 2500);
$("#accept_offer").text("Unaccept Offer");
console.log(data.status);
}
}, 'json');
} else if($("#accept_offer").text() == "Unaccept Offer") {
$.post("admin/post_offer/set_post_offer_acceptance.php", {id: offer_id, acceptance: "unaccepted"}, function(data){
if(data.status == "success") {
$("#unacceptedOfferModal").modal("show");
setTimeout(function(){ $("#unacceptedOfferModal").modal("hide"); }, 2500);
$("#accept_offer").text("Accept Offer");
console.log(data.status);
}
}, 'json');
}
}
And my class's function into:
public static function SetOfferAcceptance($offerId, $acceptance) {
if(Utilities::IsValid($offerId) && Utilities::IsValid($acceptance)) {
Database::OpenConnection();
$offerId = Utilities::SafeString(Database::$databaseConnection, $offerId);
$acceptance = Utilities::SafeString(Database::$databaseConnection, $acceptance);
$query = "";
if($acceptance == "accepted") {
$query = Database::$databaseConnection->prepare("UPDATE post_offer SET Accepted=1 WHERE Offer_ID = ?");
} else {
$query = Database::$databaseConnection->prepare("UPDATE post_offer SET Accepted=0 WHERE Offer_ID = ?");
}
$query->bind_param("i", $offerId);
$result = $query->execute();
Database::CloseConnection();
if($result) return 1; else return -1;
}
}
And that worked! :)
Thanks again #vee.
If I am not mistaken your issue stems from automatic type casting.
if($result) return 1; else return -1; // both of these evaluate to boolean true because -1 is an integer
if($result) return 1; else return 0; // evaluates to true/false respectively
if($result) return true; else return false; // evaluates to true/false respectively
The last line is what you should honestly be using.

Categories

Resources