TaneMahuta TaneMahuta - 8 days ago 4
PHP Question

PHP / Ajax: How to initiate session after successful login (rest of code working)

I am new to PHP and hope someone can help me with the following.

I am working on setting up a login page where I am using an onclick event on a button to verify the email and password ("pass") that the user entered (checking if email exists and if password matches).

So far everything works as intended but I couldn't figure out the following:
I start a session in my header file as below. Now when I verified a user's email and password ("

password correct
") I would like to pass two variables to this session so that on other pages I can see the user is already logged in. Therefore I wanted to pass a variable "
login
" as "
loggedIn
" and the user's email address as "
username
".

Can someone tell me how I can realise this here ?
Can I just do this on the ajax.php page when I already verified the user ?

How the session is being started in my header:

session_start();


The Ajax call to verify the user (in jQuery):

$.ajax({
type: "post",
url: "ajax.php",
cache: "false",
data: {
node: 'loginUser',
email: email,
pass: pass
},
success: function(data){
if(data == 'Password correct'){
// redirect to index page
window.location.href = baseURL + '/index.php?lang=' + selectedLang
}else{
alert(data);
}
},
error: function(){
}
});


The part on the ajax.php page that verifies the user with the input from the Ajax:

case "loginUser":
// login user
$email = $_POST["email"];
$pass = $_POST["pass"];

$stmt = $conn->prepare("SELECT pw FROM Users WHERE email = ? LIMIT 1");
$stmt->bind_param('s', $email);
$stmt->execute();
$result = $stmt->get_result();
if(!$result || !$result->num_rows){
echo "Email has not been registered yet";
}else{
$passHashed = $result->fetch_assoc();
if(password_verify($pass, $passHashed["pw"])){
echo "Password correct";
}else{
echo "Password incorrect";
}
}
break;


Many thanks in advance for any help with this.

Answer

On ajax.php do like this:-

<?php
session_start(); // this must be first line
case "loginUser":
    // login user
    $email = $_POST["email"];
    $pass = $_POST["pass"]; 

    $stmt = $conn->prepare("SELECT pw FROM Users WHERE email = ? LIMIT 1");
    $stmt->bind_param('s', $email);
    $stmt->execute();
    $result = $stmt->get_result();          
    if(!$result || !$result->num_rows){
        echo "Email has not been registered yet";
    }else{      
        $passHashed = $result->fetch_assoc();
        if(password_verify($pass, $passHashed["pw"])){
            $_SESSION['User']['login'] = 'loggedIn'; // assignment 
            $_SESSION['User']['username'] = $email;  // assignment
            echo "Password correct";
        }else{
            echo "Password incorrect";
        }
    }
    break;

And on any other php page:-

<?php
session_start();
echo "<pre/>";print_r($_SESSION['User']);
// rest code
?>