PHP session overlap - php

First I log in with one user and then I open a second tab and log in with other user.
Now the problem is that when I go to the tab where I logged in first and refresh it, the username from the second tab overlaps the first one.
I have seen that the two different users have different cookies, but is the second one overlapping the first one, because I try to log in with more than one user on a single machine..My theory is that I am only getting the last session and it sets it everyhwere.So I am wondering how can I make them independent.
This is my PHP code for the session of each user:
`
<?php
session_start();
if(isset($_SESSION["user_id"]))
{
$mysqli = require __DIR__ . "/databaseCon.php";
$sql = "SELECT * FROM users
WHERE user_id = {$_SESSION["user_id"]}";
$result = $mysqli->query($sql);
$user = $result->fetch_assoc();
$getSessions = $mysqli->query("SELECT sessionName FROM sessions");
}
This is my login script. Once logged in, they will be sent to different pages determined by the roles(student or a teacher):
<?php
$is_invalid = false;
#if we opened the page its set to GET, when we submit POST
if ($_SERVER["REQUEST_METHOD"] === "POST")
{
$mysqli = require __DIR__ . "/databaseCon.php";
$sql = sprintf("SELECT * FROM users
WHERE email = '%s'",
$mysqli->real_escape_string($_POST["mail"]));
$result = $mysqli->query($sql);
$user = $result->fetch_assoc();
if ($user)
{
if(password_verify($_POST["passw"], $user["password_hash"]))
{
session_start();
session_regenerate_id();
$_SESSION["user_id"] = $user["user_id"];
$_SESSION["firstName"] = $user["firstName"];
$_SESSION["privilege"] = $user["privilege"];
header("Location: /Controllers/sessionInit.php");
exit;
}
}
$is_invalid = true;
}
?>
`

When your php program feeds its session cookie to the browser, the browser then uses it, immediately, for all its tabs. So starting a session for Bob disconnects your browser from the session for Alice.
It's common during debugging to want to have two user sessions going at once. When I do that, I do one of three things
Use different browsers for different sessions (Chrome, Firefox, Edge etc).
Use a browser's anonymous mode for the second session.
Set up multiple user profiles in the browser, and use the different profiles for different sessions. This can be clunky, however.

Related

Session variables don't update on every page

On my website, there is a function for logging in and logging out. Upon login, I set the session variables pass (which is hashed password), uid which is the ID of the user logged in and loggedIn (boolean):
$hashedpass = **hashed pass**;
$_SESSION['pass'] = $hashedpass or die("Fel 2");
$_SESSION['uid'] = $uid or die("Fel 3");
$_SESSION['loggedIn'] = true or die("Fel 4");
header("Location:indexloggedin.php");
On every page, I check if the visitor is logged in by
Checking the status of $_SESSION['loggedIn'],
Searching the database for the user with the ID $_SESSION['uid'],
Checking if the hashed password in the database matches the hashed password in the session variable:
$sespass = $_SESSION['pass'];
$sesid = $_SESSION['uid'];
$sql2 = "SELECT * FROM `users` WHERE `id` = '$sesid'";
$result2 = mysqli_query($db_conx, $sql2);
$numrows2 = mysqli_num_rows($result2);
if ($numrows2 != 1) {
$userOk = false;
}
while ($row = mysqli_fetch_array($result2,MYSQLI_ASSOC)) {
$dbpass = $row['pass'];
}
if ($sespass != $dbpass) {
$userOk = false;
} else {
$userOk = true;
}
My problem is that this seems to be working on some pages, while it doesn't work at others. For example, when I log in, I am instantly logged in to the homepage, but not to the profile page. However, after a few reloads, I am logged in to the profile page as well. The same thing happens when logging out.
For testing purposes, I tried to var_dump the password variables as well as the userOk status on the index page, and this is where I noticed something interesting. When I log out, the password variables are set to be empty, and $userOk is false, according to what that is shown at index.php?msg=loggedout. But when I remove the ?msg=loggedout (and only leave index.php), the password variables are back to their previous value, and I am no longer logged out... After a few reloads, I am once again logged out.
Why is my session variables not working as expected? It feels like as if it takes time for them to update, which is very weird. I have tried with caching disabled (both through headers and through the Cache setting in my browser).
Just tell me if you need more info.
You have initialization session_start() on every Site?
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
After contacting my hosting provider, it was actually a hosting issue. It is now resolved!
Thanks,
Jacob

PHP Multiple Restricted Access

I am trying in my PHP to make it to where if the Account database value matches 0 or 1 or 2 or 3 then it makes the login go to a certain page but so far it doesn't log me in and it doesn't take me to the page. Before I had a log in page but it sent it to a universally restricted page, but what I want is depending on what the User signed up for then he gets put this value(which I have already implemented) that if this page were to work than it would send him to one of four restricted sites upon login. What I can't get is the value to get pulled and used to send him upon login to the specific page.I am using Mysqli. Here is the code:
<?php require 'connections/connections.php'; ?>
<?php
if(isset($_POST['Login'])){
$Username = $_POST['Username'];
$Password = $_POST['Password'];
$result = $con->query("select * from user where Username='$Username'
AND Password='$Password'");
$row = $result->fetch_array(MYSQLI_BOTH);
$AccountPerm = $con->query("SELECT * FROM `user` WHERE Account =
?");
session_start();
$AccountPerm = $_SESSION['Account'];
if($AccountPerm == 0){
header("Location: account.php");
}
if($AccountPerm == 1){
header("Location: Account1.php");
}
if($AccountPerm == 2){
header("Location: Account2.php");
}
if($AccountPerm == 3){
header("Location: Account3.php");
}
}
?>
so far it doesn't log me in
Just to be sure, your Account.php, Account1.php, Accout2.php and Account3.php rely on $_SESSION['Account'] right? (The code below assume so)
As for your problem with both login and redirecting you forget a line :
$_SESSION['Account'] = $row['Account'];
Also, I removed
$AccountPerm = $con->query("SELECT * FROM `user` WHERE Account =
?");
You code should look like :
<?php require 'connections/connections.php'; // NOTE: I don't close the php tag here ! See the "session_start()" point in the "Reviews" section below
if(isset($_POST['Login'])){
$Username = $_POST['Username'];
$Password = $_POST['Password'];
// TODO: Sanitize $Username and $Password against SQL injection (More in the "Reviews" section)
$result = $con->query("select * from user where Username='$Username'
AND Password='$Password'");
// TODO: Check if $result return NULL, if so the database couldn't execute your query and you must not continue to execute the code below.
$row = $result->fetch_array(MYSQLI_BOTH);
// TODO: Check if $row is NULL, if so the username/password doesn't match any row and you must not execute code below. (You should "logout" the user when user visit login.php, see the "Login pages" point in the "Reviews" section below)
session_start();
$_SESSION['Account'] = $row['Account']; // What you forgot to do
$AccountPerm = $_SESSION['Account'];
if($AccountPerm == 0){
header("Location: account.php");
}
if($AccountPerm == 1){
header("Location: Account1.php");
}
if($AccountPerm == 2){
header("Location: Account2.php");
}
if($AccountPerm == 3){
header("Location: Account3.php");
}
}
?>
Reviews
session_start()
Should be call at the top of your code. (It will probably end-up in a a shared file like connections.php that you will include in all of your file).
One reason is that session_start() won't work if you send ANY character to the user browser BEFORE calling session_start().
For exemple you close php tag after including connections.php, you may not know but you newline is actually text send to the browser !
To fix this you just have to not close your php tag, such as in
<?php require 'connections/connections.php'; ?>
if(isset($_POST['Login'])){
Login page
Make sure to logout (unset $_SESSION variables that you use to check if user is logged) the user in every case except if he enter the right username/password combinaison.
If the user is trying to login it may be a different user from the last time and we don't want him to be logged as somebody else if his username/password is wrong.
MySQL checks : You should always check what the MySQL function returned to you before using it ! (see the documentation !) Not doing so will throw php error/notification.
SQL injection : You must sanitize $Username/$Password before using them into your query.
Either you append the value with $con->real_escape_string() such as
$result = $con->query("SELECT * FROM user WHERE Account = '" . $con->real_escape_string($Username) . "' AND Password = '" . $con->real_escape_string($Password) ."')
or you use bind parameter, such as explained in this post (THIS IS THE RECOMMENDED WAY)
No multiple account pages
Your login page should redirect only to accout.php and within this page split the logic according with the $_SESSION['Account'] value.
Nothing stop you from including account1.php, account2.php, ... within account.php.
If you do so put your account1.php, account2.php, account3.php in a private folder that the user can't browse in.
(One of the method is to create a folder (such as includes) and put a file name .htaccess with Deny from all in it)

Updating user information

I know I can't use two session start codes in a same php page but for the sake of updating user account, I need the below code and I need to use session_start twice. One, to check if the user is not logged in, then redirect them and banned them from seeing the update info page and also the other session start has to be there so that my session variables could be set automatically in the update info page if the user is logged in.
anyways, I am getting this error can you guys please show me a work around way? if there's any?
thanks.
Notice: A session had already been started - ignoring session_start() in ....
<?php session_start();
if(isset($_SESSION['userid'])) {
} else {
header('Location: login.php');
}
?>
<?php
$user = $_SESSION['userid'];
$myquery = "SELECT * FROM our_users WHERE `userid`='$user'";
$result = mysqli_query($conn, $thequery);
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
session_start(); /* Basically this right here gets ignored. */
$_SESSION["user_first_name"] = $row['fn'];
$_SESSION["user_last_name"] = $row['ln'];
$_SESSION["user_email"] = $row['em'];
$_SESSION["user_password"] = $row['pw'];
?>

Having some issues on PHP login script

This code below is having a problem..
<?php
session_start();
include_once("databaseConnect.php"); // This creates $database by mysqli_connect().
if(isset($_SESSION['id'])){ // checking if user has logged in
$id = $_SESSION['id'];
$sql = "SELECT * FROM tableName WHERE id = '$id'";
$query = mysqli_query($database, $sql);
$row = mysqli_fetch_row($query);
$activated = $row[1]; // This is where I store permission for the user
if(!($activated == 2 || $activated == 3)){ // if the user has not enough permission:
header("Location: http://myWebsiteIndex.php");
}
// code for users
}else{
header("Location: http://myWebsiteIndex.php");
}
?>
I have a user who has 3 for $activated, so they should be able to access.
When a user logges in to my website, it sets $_SESSION['id'] to store the id of the user.
This session variable is used to check if the user is logged in.
However, when I run the code several time, sometimes it works and sometimes it doesn't. Sometimes, it will run the '// code for users' part, and sometimes it will just redirect to my 'http://myWebsiteIndex.php'.
How would I fix this??
First, try changing the headers to different redirects. What part of the conditional is failing? If the $_SESSION['id'] is not properly set it will redirect to the same url as it will redirect to when the user does not have proper permissions. Changing one of them will show you what part is executed when you encounter the behaviour.
Second, the comment from Barth is helpful. The if(!($activated == 2 || $activated == 2)) evaluation seems incorrect. You are evalutaing for (not) 2 or 2.
Third, take note of your session data and compare when the redirect happens to when it does not.

How to echo out info from MySQL table in PHP when sessions are being used.

I am using sessions to pass user information from one page to another. However, I think I may be using the wrong concept for my particular need. Here is what I'm trying to do:
When a user logs in, the form action is sent to login.php, which I've provided below:
login.php
$loginemail = $_POST['loginemail'];
$loginpassword = md5($_POST['loginpassword']);
$con = mysql_connect("xxxx","database","pass");
if (!$con)
{
die('Could not connect: ' .mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("SELECT * FROM Members
WHERE fldEmail='$loginemail'
and Password='$loginpassword'");
//check if successful
if($result){
if(mysql_num_rows($result) == 1){
session_start();
$_SESSION['loggedin'] = 1; // store session data
$_SESSION['loginemail'] = fldEmail;
header("Location: main.php"); }
}
mysql_close($con);
Now to use the $_SESSION['loggedin'] throughout the website for pages that require authorization, I made an 'auth.php', which will check if the user is logged in.
The 'auth.php' is provided below:
session_start();
if($_SESSION['loggedin'] != 1){
header("Location: index.php"); }
Now the point is, when you log in, you are directed BY login.php TO main.php via header. How can I echo out the user's fullname which is stored in 'fldFullName' column in MySQL on main.php? Will I have to connect again just like I did in login.php? or is there another way I can simply echo out the user's name from the MySQL table? This is what I'm trying to do in main.php as of now, but the user's name does not come up:
$result = mysql_query("SELECT * FROM Members
WHERE fldEmail='$loginemail'
and Password='$loginpassword'");
//check if successful
if($result){
if(mysql_num_rows($result) == 1){
$row = mysql_fetch_array($result);
echo '<span class="backgroundcolor">' . $row['fldFullName'] . '</span><br />' ;
Will I have to connect again just like I did in login.php?
Yes. This is the way PHP and mysql works
or is there another way I can simply echo out the user's name from the MySQL table?
No. To get something from mysql table you have to connect first.
You can put connect statement into some config file and include it into all your scripts.
How can I echo out the user's fullname which is stored in 'fldFullName' column in MySQL on main.php?
You will need some identifier to get proper row from database. email may work but it's strongly recommended to use autoincrement id field instead, which to be stored in the session.
And at this moment you don't have no $loginemail nor $loginpassword in your latter code snippet, do you?
And some notes on your code
any header("Location: "); statement must be followed by exit;. Or there would be no protection at all.
Any data you're going to put into query in quotes, must be escaped with mysql_real_escape_string() function. No exceptions.
so, it going to be like this
include $_SERVER['DOCUMENT_ROOT']."/dbconn.php";
$loginemail = $_POST['loginemail'];
$loginpassword = md5($_POST['loginpassword']);
$loginemail = mysql_real_escape_string($loginemail);
$loginpassword = mysql_real_escape_string($loginpassword);
$query = "SELECT * FROM Members WHERE fldEmail='$loginemail' and Password='$loginpassword'";
$result = mysql_query($query) or trigger_error(mysql_error().$query);
if($row = mysql_fetch_assoc($result)) {
session_start();
$_SESSION['userid'] = $row['id']; // store session data
header("Location: main.php");
exit;
}
and main.php part
session_start();
if(!$_SESSION['userid']) {
header("Location: index.php");
exit;
}
include $_SERVER['DOCUMENT_ROOT']."/dbconn.php";
$sess_userid = mysql_real_escape_string($_SESSION['userid']);
$query = "SELECT * FROM Members WHERE id='$sess_userid'";
$result = mysql_query($query) or trigger_error(mysql_error().$query);
$row = mysql_fetch_assoc($result));
include 'template.php';
Let me point out that the technique you're using has some nasty security holes, but in the interest of avoiding serious argument about security the quick fix is to just store the $row from login.php in a session variable, and then it's yours to access. I'm surprised this works without a session_start() call at the top of login.php.
I'd highly recommend considering a paradigm shift, however. Instead of keeping a variable to indicate logged-in state, you should hang on to the username and an encrypted version of the password in the session state. Then, at the top of main.php you'd ask for the user data each time from the database and you'd have all the fields you need as well as verification the user is in fact logged in.
Yes, you do have to reconnect to the database for every pageload. Just put that code in a separate file and use PHP's require_once() function to include it.
Another problem you're having is that the variables $loginemail and $loginpassword would not exist in main.php. You are storing the user's e-mail address in the $_SESSION array, so just reload the user's info:
$safe_email = mysql_real_escape_string($_SESSION['loginemail']);
$result = mysql_query("SELECT * FROM Members
WHERE fldEmail='$safe_email'");
Also, your code allows SQL Injection attacks. Before inserting any variable into an SQL query, always use the mysql_real_escape_string() function and wrap the variable in quotes (as in the snippet above).

Categories