PHP inactivity timeout and session_status() - php

I'm trying to do some protective stuff to prevent pages from accessing databases when a php page has been idle and the session has expired because of inactivity. I'm basing some of it on session_status() and am having issues with that.
Using alerts and console.log, I find the php and js code seems to be ok. When I artificially inject session_status() values, I get the results I expect.
The problem seems to be that session_start() always returns 2 (available) even after the session has timed out.
Should I not expect system_status to be updated automatically after inactivity timeouts? Is there a better way than session_status() to check for session status?
Here is the 'onclick' function that returns '2' for system_status() on an expired page when the button is clicked:
$("#save-to-database").click(function () {
var active = <?php echo session_status(); ?>;
if(active == 2) { //the session is active, do the sort & save
saveStuff();
} else { // the login has expired, abandon this and reload index.php
window.location.replace("index.php?artist=" + <?php echo $artist ?>);
}
});

This a long way to go about this but this works fine.
function isSessionActive() {
session_start();
$lastActivity=$_SESSION['lastActivity'];
if ($lastActivity!=null && ($lastActivity+(10*60) > time())) {
$_SESSION['lastActivity']=time();
return true;
} else {
deleteSession();
return false;
}
}
function deleteSession() {
session_start();
setcookie("PHPSESSID", "", time() - 3600, '/');
session_unset();
session_destroy();
}

Related

PHP session not reinitializing after logout logic

I have a problem with a session variable, I have used it well up until now but after implementing the logout logic, after relog I am unable to store my session variable again.
For the log in I use an ajax request that looks like this:
if ($row['password'] == $entered_password) {
if (!isset($_SESSION['user_email'])) {
$_SESSION['user_email'] = $entered_email;
} else {
unset($_SESSION['user_email']);
$_SESSION['user_email'] = $entered_email;
}
echo "login_validated";
exit;
} else {
echo "invalid_password";
exit;
}
and the request is:
$.post('php/login.php', {
emailLogin: emailLogin,
passwordLogin: passLogin
}, function (responseText) {
if (responseText === "invalid_username") {
alert ("Username is invalid! Please check it again or make sure you have already registered first!");
} else if (responseText === "invalid_password") {
alert ("Given password is incorrect! Please try again.");
} else if (responseText === "login_validated") {
window.location.href = "php/pages/expenses.php";
} else {
console.log(responseText);
alert ("A problem occured at te server level, please try again later! If problem persists, please contact us!");
}
});
But after implementing and using the following logic for the log out, my session variable value it's not saved and displayed anymore:
$(document).ready( function (event){
$('#logoutButton').click(function (event) {
event.preventDefault();
var user_response = confirm("Are you sure you want to logout? Your current session will be closed!");
if (user_response === true) {
<?php
if (isset($_SESSION['user_email'])) {
unset($_SESSION['user_email']);
}
session_destroy();
?>
window.location.href = "../../index.php";
}
});
});
I mention that I've first tried to use a separate file for the logout with header redirect, but was blocked by my built in adblocker similar ad-blocker error. I have supposed that maybe on my previous login actions I have made too many session variables, and proceeded to clean all my cookies. It did not had any effect. Also, read other posts and the documentation and still have no clues what I have done wrong.
Also, regarding being sure to clean all previously stored session vars, I have called once the function: http://php.net/manual/ro/function.session-unset.php session_unset. Again, no improvement seen so far. I've kept trying to read the documentation but nothing seems wrong with my code, and in aother similar forum posts I have not found anything useful. Thank you in advance!
EDIT: Short mention about the password - yes, currently they are stored in plaintext, but it is just a personal project, and upon finishing I will also implement a salt and pepper encryption on passwords.
Many thanks to you #Syscall! Almost crazed about this :) Kept everything the same, just modified the php script inside the front end to an ajax request:
`var user_response = confirm("Are you sure you want to logout? Your current session will be closed!");
if (user_response === true) {
$.ajax({url: "../logout.php", success: function(result){
console.log(result);
window.location.href = "../../index.php";
}});
}`
also added a session_start(); in the logout file. Now all the logic works, logging in, logging out, trying on different users and so on.

Executing PHP in an ''

I'm trying to execute some PHP that removes a cookie from your browser (it's used for removing your login data cookie) and when you click on the button called 'Log Out'I tried using an action to do this, but it does not seem to work this way?
<?php
if(isset($_COOKIE['LoggedIn']) && !empty($_COOKIE['LoggedIn'])) {
echo "<li>Log Out</li>";
} else {
echo "<li>Log in</li>";
}
?>
I am using the '\' to change make the quotes into regular text quotes that can be placed inside the main quotes.
So my question is mainly, how will i achieve executing it correctly? I've tried it this way but it does not do a thing.
Better still link your a href tag to a php file that runs the function you need and use
header("Location: Your URL")
To redirect back to the login page or anywhere you want
You could use something like this;
<a href='/?logout'>Logout</a>
if(isset($_GET['logout'])){ Logout(); }
function Logout() {
unset( $_SESSION[''] ); // unset and session data
session_unset(); // remove all session variables
session_destroy(); // destroy the session
setcookie("LoggedIn", "", time() - 36000, "/"); //unset the remember me cookie
header( "Location: /?loggedOut=1" );
exit;
}
As far as I'm aware anchor tags ("a" tag) have no concept of an "action" attribute. I think what you want here is "onclick" instead of "action".
Occurs to me you are also trying to execute a php function in the "action" attribute, this clearly will not work - you need to create a simple javascript function that clears out the cookie. For example:
var deleteCookie = function(name,path) {
document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;' + (path ? ' path=' + path : '');
};
Which you can then invoke in an "onclick" on your link.
I reccomend just having a logout.php button which redirects to the login page after logout button has been clicked like so:
echo "<li>Log Out</li>";
Logout.php
//Expire Cookie
setcookie('LoggedIn', '', time() - 60*100000, '/');
//Redirect to page
header( 'Location: https://www.foo.com/login.php' ) ;

cookie is not working

I set cookie in php by sending values through post but on redirect cookie, it showing that cookie is not set.
//username is just stored here for an example, it is not a good process to store credentials in cookie.
$('.loginDialogBtn').click(function() {
$usernameLogIn = $('#usernameLogIn').val();
var $passwordLogIn = $('#passwordLogIn').val();
$.post('authorizationAdmin.php', {
usernameLogIn: $usernameLogIn,
passwordLogIn: $passwordLogIn
}, function(data) {
var response = JSON.parse(data);
if (response['done'] === $usernameLogIn ) {
location.href = 'http://foodinger.in/Admin/home.php?restUsername=' + $usernameLogIn;
}
else {
$('.loginError').html('Incorrect Username and password');
}
});
});
php
if(isset($_POST['usernameLogIn']) && !empty($_POST['usernameLogIn']) && isset($_POST['passwordLogIn']) && !empty($_POST['passwordLogIn'])) {
$Username=strip_tags(trim($_POST['usernameLogIn']));
$password = strip_tags(trim($_POST['passwordLogIn']));
setcookie('username',$username, time() + (83600*30), "/Admin/", '.foodinger.in');
setcookie('restaurantId',$restId, time() + (83600*30), "/Admin/", '.foodinger.in');
}
after click on login button i can see cookie is being set in my browser but i can't fetch it using $_COOKIE.
is there any server setting which could make it wrong ?
update -- i was using "walkme" which created the problem, once i removed walkme and deleted all the cookies, it worked. Can anyone please
tell me why "walkme" is creating problem in fetching my cookie
variables
Thanks in advance
Try this to debug your cookie :
// Print an individual cookie
echo $_COOKIE["username"];
echo $HTTP_COOKIE_VARS["username"];
// Another way to debug/test is to view all cookies
print_r($_COOKIE);

PHP log out with AJAX call

I have a logout function that looks like this.
if ($_GET["argument"]=='logOut'){
if(session_id() == '') {
session_start();
}
session_unset();
session_destroy();
$host = $_SERVER['HTTP_HOST'];
$extra = 'index.php';
header("Location: http://$host/$extra");
exit;
}
My problem is that, If I inspect the page and look at the Network preview and response, it looks 'fine'.
There are two php files listed that was processed.
http://localhost:5000/inc/mainScripts.php?argument=logOut
which is where the function is located.
and http://localhost:5000/index.php
Which is where i would like to be redirected.
The Response tab in the Network of the inspect page area in chrome
contains the full login html page login.php but in the browser it remains in the same place. Like the header command has never been called.
What Am I doing wrong?
HTML AJAX call to this function:
$("#logout_btn").click(function() {
$.ajax({
url: './inc/mainScripts.php?argument=logOut'
})
});
SOLUTION
AJAX
$("#logout_btn").click(function() {
$.ajax({
url: './inc/mainScripts.php?argument=logOut',
success: function(data){
window.location.href = data;
}
});
});
PHP
if ($_GET["argument"]=='logOut'){
if(session_id() == '') {
session_start();
}
session_unset();
session_destroy();
$host = $_SERVER['HTTP_HOST'];
$link = "http://$host/index.php";
echo $link;
}
Try this instead.
if( isset($_GET['argument']) && $_GET['argument'] == 'logOut' && !empty( session_id() ) ) {
session_destroy();
header("Location: http://" . $_SERVER['HTTP_HOST'] . "/index.php");
exit;
}
Edit: If you're using AJAX, it'd be easier to send the url from your php script back to your javascript and redirect from there.
You are probably running into the same common problem that many people run into when people first start to program in PHP.
Calls to header() only works when there are NO previous HTML output generated. If there are any HTML output generated, even just a single space, calls to header() will fail. To get around this problem, use functions such as ob_start() and ob_end_flush().

Passing a $_SESSION failed when creating the $_SESSION within Ajax function

I have a simple registration form and the new comers will be registered with an ajax function. There I create a $_SESSION['is_logged'] when the registration is finished.
On var_dumb I get that the var is set. But when redirect on another page it is empty (I have included already the session_start() on the both pages...
I have read somewhere in the net that:
"Sessions are ONLY written on a page load/refresh".
Is this the case, or I have to look for some other issues within my code.
the ajax:
$.ajax({
url:"../controllers/register.php",
type:"POST",
data:res,
success: function(responce){
if (responce==1) {
$('#msg').addClass('msg-warning');
$("#form").css('display',"none");
$('#msg').append("<p>It seems that you have already submited the form. Click to "+
" <a href='login.php'>log-in</a> or to <a href='register.php'>register</a>.</p>");
}
else if (responce==2) {
$('#msg').addClass('msg-warning');
$("#form").css('display',"none");
$('#msg').append("<p>You have successfully created account. Click to "+
" <a href='start.php'>welcome</a> to start your .</p>");
$('.menu').append("<li><a href='logout.php'>Log out</a></li>")
}
else{
$('#msg').text(responce);
}
},
error: function(){
$('#msg').text("Opss, try again");
}
});
the register.php file:
if (isset($_SESSION['submited'])) {
echo 1;
exit;
}
include_once('../models/functions.php');
// Give the post parametters to another var
$arr=$_POST;
// function for uploading
$reg = registerMe($arr);
if ($reg === true) {
$_SESSION['submited']=1;
$_SESSION['is_logged']=1
echo(2);
}
else{
echo($reg);
}
exit;
The session_start(); is included in the header of the first page where from the ajax is started.And the second page - where the $_SESSION['is_logged'] is lost, again the session_start(); is part of dc_header(); function. start.php:
<?php
dc_header("Речник|Регистрация");
if (!isset($_SESSION['is_logged'])) {
#header("location: ../views/login.php");
var_dump($_SESSION);
}
?>
add
session_start();
to the top of register.php
You need to specify session_start, so your server who was commanded to execute "register.php" (either from ajax, direct call, browser scripts, cron job or whatever possible you-name-it) will handle the execution and the setting of $_SESSION variables in reference to the connected clients session. Server won't guess by itself that this is an "ajax call from an already session_start page". You need to specify that whatever is done in register.php is done in the current client's session.

Categories