Handling sessions with php question

For my project id like to start the session after they are successfully logged in and transferred to their userpage. I'm curious though how to store the session like do I use the user_id assigned to some other id or something in order to keep track of it being active. I tried reading the php docs on it but I got a bit confused. Any insight on handling sessions is most welcomed. I'll share my code for my login page so others can let me know if im doing this wrong. Thanks!
8 Replies
MD
MDOP9mo ago
<?php
include('../helpers/validateForms.php');
include('../controller/usercontroller.php');

$validator = new Validate;
$userControl = new UserController;

// validate the email and password fields for being blank then check for html entities

$options = [
'cost' => 12
];

if(isset($_POST['submit'])) {
$errors = array_filter(['email' => $validator::validateEmail($_POST['email']),
'password' => $validator::validatePassword($_POST['password'])]);

if(empty($errors)) {
$email = htmlspecialchars($_POST['email'], ENT_QUOTES | ENT_DISALLOWED, "UTF-8");
$pass = htmlspecialchars($_POST['password'], ENT_QUOTES | ENT_DISALLOWED, "UTF-8");

$encryptedPass = password_hash($pass, PASSWORD_BCRYPT, $options);

$checkUserExists = $userControl->find_User($email, $encryptedPass);

if($checkUserExists && password_verify($encryptedPass, $checkUserExists['password'])) {
session_start();

$_SESSION['id'] = $_SESSION['user_id'];
header("location:userpage.php");
}
}
}

// if validation is good, then post email and password to check against the database

// if results match database, redirect user to their web page

// if results dont match, alert the user they need to make an account.

// TODO: add check for already logged in and redirect the user.
?>
<?php
include('../helpers/validateForms.php');
include('../controller/usercontroller.php');

$validator = new Validate;
$userControl = new UserController;

// validate the email and password fields for being blank then check for html entities

$options = [
'cost' => 12
];

if(isset($_POST['submit'])) {
$errors = array_filter(['email' => $validator::validateEmail($_POST['email']),
'password' => $validator::validatePassword($_POST['password'])]);

if(empty($errors)) {
$email = htmlspecialchars($_POST['email'], ENT_QUOTES | ENT_DISALLOWED, "UTF-8");
$pass = htmlspecialchars($_POST['password'], ENT_QUOTES | ENT_DISALLOWED, "UTF-8");

$encryptedPass = password_hash($pass, PASSWORD_BCRYPT, $options);

$checkUserExists = $userControl->find_User($email, $encryptedPass);

if($checkUserExists && password_verify($encryptedPass, $checkUserExists['password'])) {
session_start();

$_SESSION['id'] = $_SESSION['user_id'];
header("location:userpage.php");
}
}
}

// if validation is good, then post email and password to check against the database

// if results match database, redirect user to their web page

// if results dont match, alert the user they need to make an account.

// TODO: add check for already logged in and redirect the user.
?>
MD
MDOP9mo ago
green
green9mo ago
im afraid i cant answer your session question, but i'd like to point out something related to the form. i am taught to use a csrf token in forms like this. a csrf token is a token that can improve security against cross site script (xss) attacks. its used to check if the form that has been sent to your validate page comes from your login page. on the login page you add something like this. you start a session, create a unique token and add it to the session
<?php
session_start();
$token = uniqid();
$_SESSION['token']= $token;
?>
<?php
session_start();
$token = uniqid();
$_SESSION['token']= $token;
?>
and in the form you add an hidden input that contains the token as value
<input type="hidden" name="csrf-token" value="<?php echo $token;?>">
<input type="hidden" name="csrf-token" value="<?php echo $token;?>">
on your validation page you compare the token value from your session with the token value from the hidden input. if its the same, you are certain that the form came from your login page
session_start();
if(isset($_SESSION["token"]) && $_SESSION["token"] == $_POST["csrf-token"]){};
session_start();
if(isset($_SESSION["token"]) && $_SESSION["token"] == $_POST["csrf-token"]){};
hope this helps :)
MD
MDOP9mo ago
interesting can the hidden field be exploited?
green
green9mo ago
technically yes, since its visible and editable in the inspector tool, but if someone changes the value it wont be equal to the value in the session only im not sure if it completely eliminates the risk of an xss attack or if there are better alternatives
MD
MDOP9mo ago
hmm well the $token value is getting echo from the above php code so the token's I think can still match? ill look into csrf tokens here's my attempt
<?php
include('../helpers/validateForms.php');
include('../controller/usercontroller.php');
include('../helpers/tokenCheck.php');

$validator = new Validate;
$userControl = new UserController;

// validate the email and password fields for being blank then check for html entities

$options = [
'cost' => 12
];

if(isset($_POST['submit'])) {
$errors = array_filter(['email' => $validator::validateEmail($_POST['email']),
'password' => $validator::validatePassword($_POST['password'])]);

if(empty($errors)) {
$email = htmlspecialchars($_POST['email'], ENT_QUOTES | ENT_DISALLOWED, "UTF-8");
$pass = htmlspecialchars($_POST['password'], ENT_QUOTES | ENT_DISALLOWED, "UTF-8");

$encryptedPass = password_hash($pass, PASSWORD_BCRYPT, $options);

$checkUserExists = $userControl->find_User($email, $encryptedPass);

if($checkUserExists && password_verify($encryptedPass, $checkUserExists['password'])) {
session_start();
$token = bin2hex(random_bytes(32));
$_SESSION['token'] = $token;
$_SESSION['id'] = $checkUserExists['user_id'];

$tokenChecker = checkToken($token);

if(!$tokenChecker) {
echo "<p>","Invalid form submission","</p>";
exit;
}

header("location:userpage.php");
exit;
} else {
echo "<p>", "Either user does not exist or password doesnt match. Please try again", "</p>";
}
} else {
echo "<p>","Please fix errors","</p>";
}
}
?>
<?php
include('../helpers/validateForms.php');
include('../controller/usercontroller.php');
include('../helpers/tokenCheck.php');

$validator = new Validate;
$userControl = new UserController;

// validate the email and password fields for being blank then check for html entities

$options = [
'cost' => 12
];

if(isset($_POST['submit'])) {
$errors = array_filter(['email' => $validator::validateEmail($_POST['email']),
'password' => $validator::validatePassword($_POST['password'])]);

if(empty($errors)) {
$email = htmlspecialchars($_POST['email'], ENT_QUOTES | ENT_DISALLOWED, "UTF-8");
$pass = htmlspecialchars($_POST['password'], ENT_QUOTES | ENT_DISALLOWED, "UTF-8");

$encryptedPass = password_hash($pass, PASSWORD_BCRYPT, $options);

$checkUserExists = $userControl->find_User($email, $encryptedPass);

if($checkUserExists && password_verify($encryptedPass, $checkUserExists['password'])) {
session_start();
$token = bin2hex(random_bytes(32));
$_SESSION['token'] = $token;
$_SESSION['id'] = $checkUserExists['user_id'];

$tokenChecker = checkToken($token);

if(!$tokenChecker) {
echo "<p>","Invalid form submission","</p>";
exit;
}

header("location:userpage.php");
exit;
} else {
echo "<p>", "Either user does not exist or password doesnt match. Please try again", "</p>";
}
} else {
echo "<p>","Please fix errors","</p>";
}
}
?>
MD
MDOP9mo ago
MD
MDOP9mo ago
helper I made to check
<?php

function checkToken($token) {
if(!$token || $token !== $_SESSION['token']) {
echo "<p>","Invalid submission","</p>";
header($_SERVER['SERVER_PROTOCOL'] . '405 Method not allowed');
exit;
return false;
}

return true;
}
<?php

function checkToken($token) {
if(!$token || $token !== $_SESSION['token']) {
echo "<p>","Invalid submission","</p>";
header($_SERVER['SERVER_PROTOCOL'] . '405 Method not allowed');
exit;
return false;
}

return true;
}
Want results from more Discord servers?
Add your server