PHP set cookie not working from include file - php

I use the following piece of code in an include file. Because it it used in two instances within my code, I wanted to separate it into another include file and use with require_once() where it is needed. However, I noticed that if I do that, the cookies won't set. Everything else seems to work though. Is this a bug or this just can't be done this way.
I have been learning PHP only for two weeks so please take it easy on me.
Thank you!
if(mysqli_num_rows($checklogin) == 1)
{
// set variables
$row = mysqli_fetch_array($checklogin);
$email = $row['Email'];
// create login sessions
$_SESSION['UserName'] = $username;
$_SESSION['Email'] = $email;
$_SESSION['LoggedIn'] = 1;
$cbxRememberMe = $_POST['cbxRememberMe'];
// if remember me is checked
if(isset($cbxRememberMe) && $cbxRememberMe == '1')
{
$row = mysqli_fetch_array($checklogin);
// create cookies for autologin
$expire = time() + AUTO_LOGIN_DURATION;
$cookie_un = sha1(sha1($row['UserName']));
$cookie_pass = sha1(sha1($row['Password']));
setcookie('user', $cookie_un, $expire);
setcookie('pass', $cookie_pass, $expire);
}
// get user's IP address
$lastloginip = $_SERVER['REMOTE_ADDR'];
// DB QUERY: update database activity
// ------------------------------------------------------------------
$updateactivity = mysqli_query($conn,"UPDATE users SET LastLoginDate = NOW(), LastActivityDate = NOW(), LastLoginIP = '$lastloginip' WHERE UserName = '$username'")
or die($updateactivity_error);
// ------------------------------------------------------------------
// redirect back to login to refresh
header('Location: login.php');
}

A require()/include()'d file will execute exactly the same as if its contents had been embedded in the file doing the require/include. A cookie header looks exactly the same whether it's directly in a file, or done via an inclue.
I'd look at whether you've actually done a mysqli query before the require once line, since you've wrapped the entire include with that if (mysqli_num_rows(... business. Perhaps you should move the query definition/execution business into the include file as well.

Related

PHP session overlap

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.

How to use $_SESSION in right way?

At the moment I am writing a little media library in PHP and i want to set sessions, so the user stays logged in and get's echoed his name at the front page.
[index.php]
if(isset($_SESSION['loggedin']))
{
//ECHO $USERNAME
}else{
echo '<p>To start, please login or register.</p>';
}
?>
I want, if theres an session id set, that PHP echoes out the $username.
[signup.php]
<?php
session_start();
$conn = mysqli_connect("$host", "$user", "$pass", "$db");
$uid = ($_POST['uid']);
$pw = ($_POST['pw1']);
$pw2 = ($_POST['pw2']);
if ($pw == $pw2) {
$sql = "INSERT INTO user (uid, pw) VALUES ('$uid', '$pw')";
$result = mysqli_query($conn, $sql);
echo "Registration succeeded.";
}else{
echo "Please check your information.";
}
header ("Refresh: 3; ../index.php");
So, after PHP successfully compares my $pw1 and $pw2 i want to start a session, then it should put the $username in the $_SESSION array.
Of course next to the secure session id.
I repeat, after this i want to echo the $username out at front page.
What is the best way to do it?
Thanks.
$sql="SELECT username FROM users WHERE userid=$uid";
$result=mysqli_query($conn,$sql);
$row=mysqli_fetch_assoc($result);
$_SESSION['username']=$row['username'];
You can do something like this.
Usage of $_SESSION super global array (compact version)
session_start(); //To init
$_SESSION['username'] = 'Bob'; // Store value
echo $_SESSION['username']; // Treat like normal array
Detailed example
To use a session, you have to init it first.
session_start();
After that you access the session vars via the super global
$_SESSION
A good way is always to store a value in your variables you want to use:
// init session
session_start();
// check if session var is set, if not init the field with value in the super global array
if(!isset($_SESSION['auth'])) $_SESSION['auth'] = false;
if(!$_SESSION['auth']) {
//do auth here like eg.
header('Location: signup.php'); // if auth is okay -> $_SESSION['auth] = true + redirect to this (main) script
die(); // This is really necessary because a header redirect can be ignored.
}
// if auth okay, do fancy stuff here
For security read the following
Remember to escape your user input, always!
How can I prevent SQL injection in PHP?
The session_id is stored in cookies normally.
Or - the old way via URL parameter.
You do not have to secure the session_id.
Read also advices about XSS/CSRF.
Plus tokens are also good.
May be this is what you mean with secure session_id.
Stackoverflow: preventing csrf in php
OWASP: https://www.owasp.org/index.php/PHP_CSRF_Guard
OWASP: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet

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)

How to connect user with a login cookie in PHP?

First of all, I am testing on localhost. I have this index.php file which contains the following "remember me" checkbox:
<input type="checkbox" id="login_remember" name="login_remember">
The login form posts to loginvalidate.php, which includes the following php script. I have included a lot of comments to ease the process of reading my code. Note that I'm pretty sure that everything below works fine.
if (isset($_POST['login_submit'])) { //SETS VARIABLES FROM FORM
$email = $_POST[trim('login_email')];
$password = $_POST['login_password'];
$remember = isset($_POST['login_remember']) ? '1' : '0';
$db_found = mysqli_select_db($db_handle,$sql_database); //OPENING TABLE
$query = "SELECT password FROM registeredusers WHERE email = '$email'";
$result = mysqli_query($db_handle, $query) or die (mysqli_error($db_handle));
$row = mysqli_fetch_assoc($result);
$numrows = mysqli_num_rows($result);
if ($numrows!=0) //IF EMAIL IS REGISTERED
{
if ($row['password'] == $password) { //IF PASSWORD IN DATABASE == PASSWORD INPUT FROM FORM
if ($remember == '1'){ //IF USER WANTS TO BE REMEMBERED
$randomNumber = rand(99,999999); //RANDOM NUMBER TO SERVE AS A KEY
$token = dechex(($randomNumber*$randomNumber)); //CONVERT NUMBER TO HEXADECIMAL FORM
$key = sha1($token . $randomNumber);
$timeNow = time()*60*60*24*365*30; //STOCKS 30 YEARS IN THE VAR
$sql_database = "registeredusers";
$sql_table = "rememberme";
$db_found = mysqli_select_db($db_handle,$sql_database); //OPENING TABLE
$query_remember = "SELECT email FROM rememberme WHERE email = '$email'"; //IS THE USER IN TABLE ALREADY
$result = mysqli_query($db_handle, $query_remember) or die (mysqli_error($db_handle));
if (mysqli_num_rows($result) > 0) { //IF USER IS ALREADY IN THE REMEMBERME TABLE
$query_update = "UPDATE rememberme SET
email = '$email'
user_token = '$token'
token_salt = '$randomNumber'
time = '$timeNow'";
}
else { //OTHERWISE, INSERT USER IN REMEMBERME TABLE
$query_insert = "INSERT INTO rememberme
VALUES( '$email', '$token', '$randomNumber', '$timeNow' )";
}
setcookie("rememberme", $email . "," . $key, $timenow);
}
header('Location: homepage.php'); //REDIRECTS: SUCCESSFUL LOGIN
exit();
}
Then, when I close the internet browser and come back to index.php, I want the cookie to automatically connect the user. This is in my index.php:
include 'db_connect.php';
$sql_database = "registeredusers";
$db_found = mysqli_select_db($db_handle,$sql_database); //OPENING TABLE
session_start();
if (isset($_COOKIE['rememberme'])) {
$rememberme = explode(",", $_COOKIE["rememberme"]);
$cookie_email = $rememberme[0];
$cookie_key = $rememberme[1];
$query_remember = "SELECT * FROM rememberme WHERE email = '$cookie_email'"; //IS THE USER IN TABLE ALREADY
$result_remember = mysqli_query($db_handle, $query_remember) or die (mysqli_error($db_handle));
$row = mysqli_fetch_assoc($result_remember);
$token = $row['user_token'];
$randomNumber = $row['token_salt'];
$key = sha1($token . $randomNumber); //ENCRYPT TOKEN USING SHA1 AND THE RANDOMNUMBER AS SALT
if ($key == $cookie_key){
echo "lol";
}
}
The problem is, it never echoes "lol". Also, does anyone have any insight on how I could connect the users? AKA, what should go inside these lines:
if ($key == $cookie_key){
echo "lol";
}
Thank you! I'm still new to PHP and SQL so please bear with me if I have made some beginner errors.
EDIT!: After looking again and again at my code, I think that my error might lie in these lines. I'm not sure about the syntax, and the method I am using to store values into $token and $randomNumber:
$query_remember = "SELECT * FROM rememberme WHERE email = '$cookie_email'"; //IS THE USER IN TABLE ALREADY
$result_remember = mysqli_query($db_handle, $query_remember) or die (mysqli_error($db_handle));
$row = mysqli_fetch_assoc($result_remember);
$token = $row['user_token'];
$randomNumber = $row['token_salt'];
A login script in PHP can be implemented using sessions.
Using Sessions
Making it simple, sessions are unique and lives as long as the page is open (or until it timeouts). If your browser is closed, the same happens to the session.
How to use it?
They are pretty simple to implement. First, make sure you start sessions at the beginning of each page:
<?php session_start(); ?>
Note: It's important that this call comes before of any page output, or it will result in an "headers already sent" error.
Alright, now your session is up and running. What to do next? It's quite simple: user sends it's login/password through login form, and you validate it. If the login is valid, store it to the session:
if($validLoginCredentials){
$_SESSION['user_id'] = $id;
$_SESSION['user_login'] = $login;
$_SESSION['user_name'] = $name;
}
or as an array (which I prefer):
if($validLoginCredentials){
$_SESSION['user'] = array(
'name' => $name,
'login' => 'login',
'whichever_more' => $informationYouNeedToStore
);
}
Ok, now your user is logged in. So how can you know/check that? Just check if the session of an user exists.
if(isset($_SESSION['user_id'])){ // OR isset($_SESSION['user']), if array
// Logged In
}else{
// Not logged in :(
}
Of course you could go further, and besides of checking if the session exists, search for the session-stored user ID in the database to validate the user. It all depends on the how much security you need.
In the simplest application, there will never exist a $_SESSION['user'] unless you set it manually in the login action. So, simply checking for it's existence tells you whether the user is logged in or not.
Loggin out: just destroy it. You could use
session_destroy();
But keep in mind that this will destroy all sessions you have set up for that user. If you also used $_SESSION['foo'] and $_SESSION['bar'], those will be gone as well. In this case, just unset the specific session:
unset($_SESSION['user']);
And done! User is not logged in anymore! :)
Well, that's it. To remind you again, these are very simple login methods examples. You'll need to study a bit more and improve your code with some more layers of security checks depending on the security requirements of your application.
reason behind your code is not working is
setcookie("rememberme", $email . "," . $key, $timenow); // this is getting expire exactly at same time when it is set
replace it with
setcookie("rememberme", $email . "," . $key, time() * 3600);//expire after 1hour
time()*60*60*24*365*30
this time is greater than 9999 year also you didn't need to set this horror cookie time.
that cookie time you were set is greater than 9999 years and php not allow for this configure.
in my opinion the best solution is setup new expire cookie time lower than 9999 :))

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