PHP session not reinitializing after logout logic - php

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.

Related

Cannot get ajax post to work

I am able to the js file to fire which does do the first alert but i cannot get the 2nd alert to happen, php file is there and working returning 0 but the alert('finished post'); is not coming up. I think its some syntax I am missing.
$(function () {
$("#login_form").submit(function () {
alert('started js');
//get the username and password
var username = $('#username').val();
var password = $('#password').val();
//use ajax to run the check
$.post("../php/checklogin.php", { username: username, password: password },
function (result) {
alert('finished post');
//if the result is not 1
if (result == 0) {
//Alert username and password are wrong
$('#login').html('Credentials wrong');
alert('got 0');
}
});
});
});
Here is the php
session_start();
include 'anonconnect.php';
// username and password sent from form
$myusername= $_POST['username'];
$mypassword= $_POST['password'];
$sql = $dbh->prepare("SELECT * FROM Users WHERE UserLogin= :login");
$sql->execute(array(':login' => $myusername));
$sql = $sql->fetch();
$admin = $sql['admin'];
$password_hash = $sql['UserPass'];
$salt = $sql['salt'];
/*** close the database connection ***/
$dbh = null;
if(crypt($mypassword, $salt) == $password_hash){
// Register $myusername, $mypassword and redirect to file
$_SESSION['myusername'] = $myusername;
$_SESSION['loggedin'];
$_SESSION['loggedin'] = 1;
if($admin == 1){
$_SESSION['admin'] = 1;
}
header("location:search.php");
}
else {
$_SESSION['loggedin'];
$_SESSION['loggedin'] = 0;
echo 0;
}
Ok so I'll take a stab at this, see if we can work this out. First, let's clean up your code a little bit - clean code is always easiest to debug:
$(function () {
$("#login_form").on('submit', function(){
console.log('form submitted');
// get the username and password
var login_info = { username: $('#username').val(), password: $('#password').val() }
// use ajax to run the check
$.ajax({
url: '../php/checklogin.php',
type: 'POST',
data: login_info,
success: loginHandler
error: function(xhr, status, err){ console.log(xhr, status, err); }
});
return false;
});
function loginHandler(loggedIn){
if (!loggedIn) {
console.log('login incorrect');
} else {
console.log('logged in');
}
}
});
...ok great, we're looking a little better now. Let's go over the changes made quickly.
First, swapped alerts for console.logs - much less annoying. Open up your console to check this out -- command + optn + J if you're using Chrome.
Second, we compressed the login info a bit - this is just aesthetics and makes our code a little cleaner. Really you should be using variables when they need to be used again, and in this case you only use them once.
Next, we swapped the $.post function for $.ajax. This gives us two things -- one is a little finer control over the request details, and the second is an error callback, which in this case is especially important since you almost certainly are getting a server error which is your original problem. Here are the docs for $.ajax for any further clarification.
We're also pointing the success handler to a function to minimize the nesting here. You can see the function declared down below, and it will receive the data returned by the server.
Finally we're returning false so that the page doesn't refresh.
Now, let's get to the issue. When you use this code, you should see a couple things in your console. The first will probably be a red message with something like 500 internal server error, and the second should be the results of the error callback for the ajax function. You can get even more details on this in Chrome specifically if you click over to the Network Tab and look through the details of the request and response.
I can't fix your PHP because you didn't post it, but I'll assume you'll either follow up with an edit or figure that out yourself. Once you have the server issue ironed out, you should get back a clean console.log with the response you sent back, and you can move ahead.
Alternately, this will work because of the lack of page refresh in which case you can ignore the previous 2 paragraphs and declare victory : )
Hope this helps!
Ah, so damned obvious. You aren't cancelling the default submit action so the form is submitting normally. Add this
$("#login_form").submit(function (e) {
e.preventDefault();
// and so on
See http://api.jquery.com/event.preventDefault/
you need to change 2nd line and add the e.preventDefault to prevent the form from refreshing the whole page.
$("#login_form").submit(function (e) {
e.preventDefault();
Also I would change the AJAX request to use GET and change the code in PHP to read variables from GET so you can easily test the PHP page is working by running it in the browser like this
checklogin.php?username=x&password=y
try this:
$("#login_form").submit(function () {
alert('started js');
//get the username and password
var username = $('#username').val();
var password = $('#password').val();
//use ajax to run the check
$.post("../php/checklogin.php", { username: username, password: password }, function (result) {
alert('finished post');
//if the result is not 1
if (result == '0') {
//Alert username and password are wrong
$('#login').html('Credentials wrong');
alert('got 0');
}
}, 'text');
});
}, 'text');
maybe the server does not give the right data format. for example, if you request for json, and the jQuery cannot convert result sting to json. then the function would not be executed and then you would not able to get 'alert('got 0');' thing.

'window.location.replace' redirects to the given page but destroies the session from php (Chrome only)?

I know that the question is a bit confusing but here is the case.
I have the following Ajax function:
$.ajax({
url:"../controllers/xx_register.php",
type:"POST",
data:send,
success: function(response){
if (response=="1") {
window.location.replace("http://localhost/Underground/01.InProgress/ES-dictionary/public/index.php");
return true;
}
else{
$('#error').append(response);
}
},
error: function(){
$('#error').append('Fatal error!');
}
});
return false;
the xx_register.php file:
$arr=$_POST;
$reg = registerMe($arr);
if ($reg === true) {
$_SESSION['is_logged']=$arr['username'];
echo 1;
exit();
}
else{
echo($reg);
exit();
}
finally the index.php
session_start();
if (isset($_SESSION['is_logged'])) {
header("Location: ../views/start.php");
exit();
}
else{
header("Location: ../views/login.php");
exit();
}
Shortly - the idea:
I use ajax function for registering a new users. If everything is ok with the registration the user will be redirected to index.php. As the $_SESSION['is_logged'] exist the user will be redirected to the start.php page.
This all works for FireFox 21, IE 10, Safari 5.1 but on Chrome 27 the thing are quite different - the user is again redirected to loggin.php. The simple logic is pointing that window.location.replace is redirecting to index.php and clearing the session. I really don't see any explanation.
Two questions:
1. Am I correct about the issue with the window.location.replace?
2. How to fix it?
Thanks a lot.
Don't use .replace() for this, just assign the value directly.
This is fix:
window.location = "http://localhost/Underground/01.InProgress/ES-dictionary/public/index.php";

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.

pass 2 variables from 1 function to another in jquery

OK, I'm getting the results of a PHP form from JSON to do a login validation. I want to check to see if their account is activated, which I do just fine. If it's not I show a jQuery error but I want the ability to let them resend the activation email. I can pass the username password to the function displaying the error with JSON, but how do I then pass that data to a new function to process the new email? Here is what I have so far:
// LOGIN Validation
$(function(){
$("#jq_login").submit(function(e){
e.preventDefault();
$.post("widgets/login_process.php", $("#jq_login").serialize(),
function(data){
if(data.all_check == 'invalid'){
$('div.message_error').hide();
$('div.message_success').hide();
$('div.message_error').fadeIn();
$('div.message_error').html(
"<div>UserId and/or password incorrect. Try again.</div>"
);
} elseif(data.user_check == 'invalid'){
$('div.message_error').hide();
$('div.message_success').hide();
$('div.message_error').fadeIn();
$('div.message_error').html(
"<div>UserId and/or password incorrect. Try again.</div>"
);
} elseif (data.activated_check == 'invalid'){
$('div.message_error').hide();
$('div.message_success').hide();
$('div.message_error').fadeIn();
$('div.message_error').html(
"<div>Your account has not been activated. Please check your " +
"email and follow the link to activate your account. Or click " +
"<a href='#' id='resend'>here</a> to re-send the link.</div>"
);
} else {
$('div.message_error').hide();
$('div.message_success').fadeIn();
$('div.message_success').html(
"<div'>You are now logged in. Thank you </div>"
);
window.location.replace("producer.php");
return false;
}
}, "json");
});
});
$(function(){
$("#resend").live('click', function(event){
event.preventDefault();
alert(data.username);
var data = 'username=' + data.username + 'password=' + data.password;
$.ajax
});
});
I'm new so I don't understand all the ins and outs of passing data back and forth.
thank you.
craig
With Ajax there's not really "passing data back and forth," but rather just passing callbacks. That's what you're doing when you put function() { ... } as a function parameter--you're creating a callback.
I think the best course of action is to refactor this into several stand-alone functions. A good best practice is to make each function do one thing only, rather than defining functions within functions within functions.
Once refactored, it becomes more clear how we can "reuse" the username and password for the resend-activation link.
(function() { // to keep these functions out of the global scope(†)
// this will be called when the login form is submitted
function handleLogin(evt) {
evt.preventDefault();
// same as your code except that instead of creating a function here
// we instead pass `handleLoginResponse`, which is a function we'll
// define later
$.post( 'widgets/login_process.php',
$(this).serialize(), // <-- In events, `this` refers to the element that
handleLoginResponse, // fired the event--in this case the form, so we
'json' // don't need its id, we can just give `this`
); // to jQuery.
}
// This is the function we gave to $.post() above, and it'll be called when
// the response is received.
function handleLoginResponse(data) {
// Here we decide what message to show based on the response, just like
// in your code, but we call a function (showError or showSuccess) to
// avoid repeating ourselves.
if(data.all_check == 'invalid') {
showError("UserId and/or password incorrect. Try again.");
} else if(data.user_check == 'invalid') {
showError("UserId and/or password incorrect. Try again.");
} else if(data.activated_check == 'invalid') {
showError("Your account has not been activated. Please check your " +
"email and follow the link to activate your account. Or " +
"click <a href='#' id='resend'>here</a> to re-send the link."
);
} else {
showSuccess("You are now logged in. Thank you.");
redirectToLoggedInPage();
}
}
// the function that shows error messages
function showError(message) {
$('.message_success').hide();
$('.message_error').hide(). // jQuery chaining keeps things tidy
html('<div>' + message + '</div>').
fadeIn();
}
// the function that shows success messages
function showSuccess(message) {
$('div.message_error').hide();
$('div.message_success').fadeIn().
.html('<div>' + message '</div>');
}
// this method is called when the "resend" link is clicked
function handleResendClicked(evt) {
evt.preventDefault();
// send another Ajax request to the script that handles resending, using
// the form values as parameters
$.get( './resend_activation.php',
$('#jq_login').serialize(),
handleResendResponse // again we've defined this function elsewhere
);
}
// called when the Ajax request above gets a response
function handleResendResponse(data) {
// of course you can do whatever you want with `data` here
alert('resend request responded with: ' + data);
}
// called from handleLoginResponse when the login is successful
function redirectToLoggedInPage() {
window.location = './producer.php';
}
// finally, our document.ready call
$(function() {
// pass the names of the functions defined above to the jQuery
// event handlers
$("#jq_login").submit(handleLogin);
$("#resend").live('click', handleResendClicked);
});
}());
Of course, you won't always code like this--sometimes it really is best to just define an anonymous function() { ... } on the spot--but when things are getting nested three-levels deep this is a good way to untangle things and tends to make the way forward more clear.
(†) Anonymous closures for limiting scope
Could the server simply append the confirmation link with the returned json?
$('div.message_error').html(
"<div>Your account has not been activated. Please check your " +
"email and follow the link to activate your account. Or click " +
"<a href='" + data.activation_url + "' id='resend'>here</a> to re-send the link.</div>"
);

returning php session to ajax

I am having trouble getting jQuery ajax to recognise a session. I am creating a php session from a login script, but what is happening is that when ajax loads the authenticated page, the session is always unset. For example, in the secure page, if I refresh the page, the session id changes each time. I have session_start(); in each page. Can someone please show me the correct way to handle sessions with ajax and php? I have spent 2 days and have used google so much, I will probably get an invite to there xmas lunch :-) I have included the relevant code and would be grateful for any help. Thanks
PS. If it makes any difference, I am trying to develop mobile app using jquery mobile.
login html js
$(function() {
$("#kt_login1").click(function() {
var user = $('#user').val();
var pass = $('#pass').val();
if (user == '') {
$("#login_message").html('This field cannot be empty')
$('label[for=user]').addClass("label")
return false;
}
else if (pass == '') {
$("#login_message").html('This field cannot be empty')
$('label[for=pass]').addClass("label")
return false;
}
else $('label[for=user]').removeClass("label");
$('label[for=pass]').removeClass("label");
//alert(user + pass + ok);
data = 'user=' + user + '&pass=' + pass;
$.ajax({
type: "POST",
url: "testajax.php",
cache: false,
data: data,
success: function(data) {
if (data == 'authenticated') {
//alert(user);
document.location = 'secure.php';
}
else $('#login_message').html('You are not authorised');
//$(ok).val('Logged In');
//$("#login").get(0).reset();
//$("#form").dialog('close');
},
error: function(xhr, ajaxOptions, thrownError) {
jAlert('There was an exception thrown somewhere');
alert(xhr.status);
alert(thrownError);
}
});
return false;
});
});
testajax.php
<?php
// test wether the user session is already set
$username = mysql_real_escape_string($_POST['user']);
$pass = mysql_real_escape_string(md5($_POST['pass']));
mysql_connect('localhost', 'root', '');
mysql_select_db('sample');
//now validating the username and password
$sql="SELECT * FROM user_usr WHERE username_usr='$username' and password_usr='$pass'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
//if username exists
if(mysql_num_rows($result)>0) {
session_start();
$_SESSION['u_name']=$row['name_usr'];
/*
echo '<pre>';
print_r( $_SESSION['u_name'] );
print_r( $_REQUEST );
echo '</pre>';
exit;
*/
echo 'authenticated';
}
else
{
echo 'Unknown User';
}
?>
+++++SOLUTION+++++
Changed form input from submit to button and voila. All ok
you have to call session_start() each time working with a session (not only when creating it)
see: http://php.net/manual/en/function.session-start.php
There are a whole load of reasons this might be the case - but you're code is upside down! This may well be the cause (or a contributory factor).
You should not treat the existence of a session as evidence of authentication (the contents of the session is another thing altogether). Call session_start() at the top of your script - not conditionally, half-way through.
As to why your session data is not available...that's an FAQ here - have a look at some of the previous answers for potential causes / how to investigate.

Categories