0

On my website I only use ajax-calls to save and get data.

I am also using ajax with my login. So this is what I do:

FILE -> ajaxLogin.js

if (check === true) {
    $.ajax({
        type: 'POST',           
        url: 'PHPCalls.php?CallID=Login',
        data: $("#formLogin").serialize(),
        success: function(data) {                    
            var result = $.trim(data);
            if(result !== 'false') {
                $("#spinner").hide();
                window.location.replace(result);
            }
            else if(result === 'false') {
                $("#spinner").hide();
                alert('No match');
            }
        }
    });
}

FILE -> PHPCalls.php

if(isset($_GET['CallID']))
{
    //LOGIN
    if ($_GET['CallID'] == 'Login') {
        loginFromForm();
    }
}

FILE -> functions.php -> loginFromForm()

function loginFromForm() {
    if($_SERVER['REQUEST_METHOD'] == 'POST') {
        if(isset($_POST['riziv']) && isset($_POST['password'])) {
            $riziv = htmlentities($_POST['riziv']);
            $password = htmlentities($_POST['password']);

            if (loginMember($riziv, $password) == true) {
                //Login success
                if(isset($_SESSION['oldURL'])) {
                    echo $_SESSION['oldURL'];
                } else {
                    echo 'adminpanel.php';
                }
            } else {
                echo 'false';
            }
        } else { 
            // The correct POST variables were not sent to this page.
            echo 'false';
        }
    }
}

FILE -> functions.php -> loginMember($riziv, $password)

function loginMember($riziv, $password) {
    // Using prepared statements means that SQL injection is not possible.
    $db = MysqliDb::giveNewDbConnection();
    $data = array('ID', 'Firstname', 'Admin', 'Salt', 'Password');
    $db->where('RIZIV', $riziv);
    if ($result = $db->getOne('tblMember')) {
        $memberID = $result['ID'];
        $firstname = $result['Firstname'];
        $admin = $result['Admin'] = 1 ? true : false;
        $salt = $result['Salt'];
        $db_password = $result['Password'];

        // hash the password with the unique salt.
        $password = hash('sha512', $password . $salt);

        if ($db->count == 1) {
            // If the user exists we check if the account is locked
            // from too many login attempts
            if (checkBrute($memberID) == true) {
                // Account is locked 
                // Send an email to user saying their account is locked
                return false;
            } else {
                // Check if the password in the database matches
                // the password the user submitted.
                if ($db_password == $password) {
                    // Password is correct!
                    // Get the user-agent string of the user.
                    $user_browser = $_SERVER['HTTP_USER_AGENT'];
                    // XSS protection as we might print this value
                    $memberID = preg_replace("/[^0-9]+/", "", $memberID);
                    $_SESSION['memberid'] = $memberID;
                    // XSS protection as we might print this value
                    $username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $firstname);
                    $_SESSION['username'] = $username;
                    $_SESSION['admin'] = $admin;
                    $_SESSION['riziv'] = $riziv;
                    $_SESSION['login_string'] = hash('sha512', $password . $user_browser);
                    // Login successful.
                    return true;
                } else {
                    // Password is not correct
                    // We record this attempt in the database
                    $now = time();
                    $db = MysqliDb::giveNewDbConnection();
                    $data = array("MemberID" => $memberID, "Time" => $now);
                    $db->insert('tblLoginAttempts', $data);
                    return false;
                }
            }
        } else {
            // No user exists.
            return false;
        }
    }
}

FILE -> adminpanel.php (I add this snippet with an include on every page)

<?php
sec_session_start();

if(login_check() == false) {
    header('location: index.php');
}
//redirects to a specific url
if (($_SERVER['REQUEST_URI'] != 'index.php') && ($_SERVER['REQUEST_URI'] != $_SESSION['oldURL'])) {
    $_SESSION['oldURL'] = $_SERVER['REQUEST_URI'];
}
?>
//START THE HTML

FILE -> functions.php -> sec_session_start()

function sec_session_start() {
    $session_name = 'sec_session_id';
    $secure = false;
    $httponly = true;
    if (ini_set('session.use_only_cookies', 1) == FALSE) {
        header("Location: admin/error.php?err=Could not initiate a safe session (ini_set)");
        exit();
    }
    $cookieParams = session_get_cookie_params();
    session_set_cookie_params($cookieParams['lifetime'],
        $cookieParams['path'],
        $cookieParams['domain'],
        $secure,
        $httponly);
    session_name($session_name);
    session_start();
    session_regenerate_id(true);
}

RESULT OF print_r($_SESSION);

Array
(
    [oldURL] => /hijw/admin/adminpanel.php
)

If the login is succesful I get 'adminpanel.php' as result to that is where my page is redirected to. This all works fine but the problem starts at the adminpanel.php: although I use session_start() my session variables like id, username, login_string, ... have dissapeared.

I have read about an issue with asp.net where u can't pass session variables over ajax. Is that the same with php? Is there a way to solve it?

13
  • 1
    You should post the code of 'adminpanel.php'. Commented Sep 3, 2014 at 12:54
  • Session cookie is passed fine over ajax, so your problem lies elsewhere Commented Sep 3, 2014 at 12:54
  • Can you also show us your PHPCalls.php (I'm assuming that you are running session_start() in both PHPCalls.php and adminpanel.php) Commented Sep 3, 2014 at 12:55
  • @ManishJ updated with other snippets. Commented Sep 3, 2014 at 13:06
  • @nettux443 I added the rest Commented Sep 3, 2014 at 13:11

1 Answer 1

1

I have reviewed your code. Everything is perfect . But the problem is when you are assigning the session in "FILE -> functions.php -> loginMember($riziv, $password)". It will not be available to every pages beacuse you are requesting through ajax.

There is two way to resolve it either reload the page after successful login OR return the value from "FILE -> functions.php -> loginMember($riziv, $password)" and reset session in

"FILE -> adminpanel.php"

I hope you will get help from my response.

Sign up to request clarification or add additional context in comments.

5 Comments

thx, I'll try this out. So if I would just work with POST instead of ajax, the problem should be solved as well?
Yes. Sure you can try it too.
Hello, I got it working with a POST-submit. I first tried reloading the login-page with ajax instead of directly going to adminpanel but the session-variables were still not created except for 'oldURL'. What do you mean by reset session in adminpanel.php ?
I got another question/remark related to this. I also have a 'change-password'-form where I'm using ajax to call for the changePassword($oldpass, $newpass) function. In that function I have to replace the old $_SESSION['login_string'] created by a hash512 with the password and browser. There I can change that session variable...Is that logical?
You can assign in session. But you have to reload and ask the the user to login again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.