Don't understand why $_SESSION is needed - php

I tried to create a login form from an example. I made it works but I don't understand.
Why $_SESSION['umsco'] is required and why should I assign the $username variable to it. I also do not understand if conn->close() required and what is the $result variable.
// I include the database file so we can get the information from there and apply it in here as well.
include "dbc.php";
// here we select the variables we want from the table 'members'.
$sql = "SELECT id, firstName, lastName FROM members";
// here we do something that I dont really know but this is standard procedure.
$result = mysqli_query($conn, $sql);
// declaring username
$username = $_POST["username"];
$password = $_POST["password"];
// my result thing, again, standard procedure.
$result = $conn->query($sql);
// we insert all values in row, standard procedure.
$row = $result->fetch_assoc();
// here we check if the username is the same as the database.
if ($username == $row["firstName"]) {
// if it's correct then we start a session
session_start();
// we give a session some random letters or numbers and set it to $username, not exactly sure why, but it wont work without it.
$_SESSION['umsco'] = $username;
// we change the location to secrect.php
header("location: secret.php");
}
// we close the connection, not sure if this is needed, but it seems logical.
$conn->close();

I advise you to always implement session_start()at the beginning of your code to avoid bad behavior.
What is a session
To understand, you must understand what a PHP session is.
A session is a way to keep variables on all pages of your site for a current user.
How it work
First you must ask PHP to initialize the session. For doing this, you must add session_start() at the beginning of your code.
When the server responds to the client, it append a cookie called PHPSESSID who contains the unique session identifier of the user.
At every request, the browser sends this cookie to the server so that php can recover the session from the hard disk of the server.
The most commun way to register a session variable is $_SESSION['key'] = $value;.
Final answer
To end, the line $_SESSION['umsco'] = $username; store the username of the user in his session until.
the session is destroyed with session_destroy()
the session expire after a time defined in php.ini
you unregister the variable.
In secret.php you probably check whether this value is assigned or if the session exists to check if the user is logged in. That's why it's mandatory, otherwise a login form would have no meaning.
Another ressource : Is closing the mysql connection important?

The result thing is that next time you call
session_start();
$loggedUserName = $_SESSION['umsco'];
you will have that user (username) available for you wherever you need it.
Just read basics of SESSION and you should be able to understand that.

Firstly, you need to query members where username and password match $_POST data.
Secondly, whatever is stored in $_SESSION variable will be available between requests. Typically, you want to "remember" user ID or similar so you do not need to submit username/password and repeat the member lookup with every request.
See more elaborate description here: https://www.johnmorrisonline.com/build-php-login-form-using-sessions/

What others have said about the $_SESSION variable is correct. If using session_start(); those values can be persisted across multiple requests from the users browser. The $_SESSION value will be particular to the user visiting your site.
Regarding the $result object, $result->fetch_assoc(); will only fetch one row from your table. So your current code would only work if the username matches the 1st row of your members table. It'd be best to query only rows where the username matches what they've entered. Note there's a big security risk if you just concatenate strings together for the query, so you should use prepared statements (https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection)

Related

PHP $_SESSION, trying to access users table displays no output and when session is killed the session remains active

i'm trying to a build a secure sessionID.
Usually i store the UserID as the $_SESSION['session'];, now im not too sure if it is really secure to have the userID as the sessionID. so what i have done is tested this theory although now i cannot access the users information and after i kill the session the sessions are still active and available?
CODE to check login if true or false:
if(password_verify($userPass, $user['userPasswd']))
{
session_start();
$UID = str_replace($user['text'].$user['text1'], '', $user['uniqID']);
$_SESSION['SESSION'] = sha1(md5(sha1($UID)));
return true;
} else {
return false;
}
Logout Script: EDIT fixed using $_SESSION = array();
public function userLogout()
{
session_destroy();
unset($_SESSION['SESSION']);
return true;
}
Script to access users table information (username, email etc):
$userID = $_SESSION['SESSION'];
$stmt = $userClass->runQuery("SELECT * FROM users WHERE uniqID=:userID");
$stmt->execute(array(":userID"=>$userID));
$user = $stmt->fetch(PDO::FETCH_ASSOC);
print_r($_SESSION['SESSION']); //Prints out session even if not logged in
print $user['Username']; //Prints out nothing
i'm not sure if i missed a step or if hashing a session is even necessary, maybe i am doing something incorrectly. Essentially i am trying to secure the userID via a hash instead of having it displaying the users actual ID. Using the hash i would like to match and gain access to the users column.
ADDITIONAL NOTE: if i change the session to get the actual userID eg: 1
$userID = 1; //i did set the $_SESSION var to the userID to check if logout works
$stmt = $userClass->runQuery("SELECT * FROM users WHERE userID=:userID");
$stmt->execute(array(":userID"=>$userID));
$user = $stmt->fetch(PDO::FETCH_ASSOC);
print_r($_SESSION['SESSION']); //prints out 1 //still does not destroy session after userLogout() is initiated
print $user['Username']; //Prints username which is correct
been boggled by this for hours, maybe a different set of eyes and experience might help x_x.
(this is a comment, but its a bit long)
As ADyson says, this is very confused coding. Neither your code nor your narrative explain what you are trying to achieve here. What is the threat model? What is your definition of "secure"? $_SESSION['SESSION'] is not the session id.
If you store a static map between the (effectively random, but not random enough) identifier stored in the session and the username, then all you've done is limit the performance and scalability of the system - I cannot see how it adds any value for security.
There is a usage model where you might want a warrant-proof user database, where you would hash usernames - but this is not it.
There are models for protecting the session data from other subscribers on a shared host (with poor partitioning). This is not that either.
There are models for ensuring that session data is protected in backups....and, nope, this isn't very good for that either.
sha1(md5(sha1($UID)));
This is silly.
Take some time to understand how the default session handler actually works before you start trying to improve it by throwing code at it (hint: there are things in there which are not suitable for every application, but if you want to improve them, use a custom handler - not wrapping the default handler in additional code). But before you write any code, you need to get your head around exactly what you are trying to achieve.
You need to follow such way:
session_start();
// Unset all of the session variables.
$_SESSION = array();
// Finally, destroy the session.
session_destroy();

PHP Session Variable not Available

I have a PHP file (approvals.php) that only gets executed on an AJAX call. It has a postgresql query that searches a table and uses a customer id, which is set as a session variable. Problem is, it seems I can't access this session variable in this file. My query is like:
$query = "SELECT merchant_id FROM ndovu_merchant_users WHERE customer_id={$_SESSION['customer_id']}";
$result = pg_query($query);
I have tried to echo the session variable $_SESSION['customer_id'] but nothing. However on passing a fixed value to the query, it returns a result.
In your case, i would have checked if the session is set in the first place.
//this should be put at the header of the page
session_start();
if(isset($_SESSION['customer_id']) && !empty($_SESSION['customer_id'])){
echo $_SESSION['customer_id'];
}else{
echo 'session is not set';
}
You need to place session_start(); above the code section where you use it; the top of the page is usually the best place to place it.
Also, it should be noted; you have what is potentially a large security flaw here, by passing in unescaped data.
You should look into using prepared statements if possible; or at least escape your inputs.
The user session is not accesed when the script is called by an ajax request.
The session token wich php requires to obtain the session data is stored in the client side(user) inside a session cookie.
You can read more here
https://stackoverflow.com/a/1535712/3922692
Just pass the user id with GET or POST in the ajax request.
There is not enough code presented but if you realy need to get the id from the session you can use an iframe (which is not recommended), process fetch data server side and output it in the iframe.

Redirect loop on login script PHP

I have a login system that whenever the user logs succesfully creates some cookies with his username password and some other variables that are put in the url for configuration of the session:
setcookie("username", $myusername); //Sets a cookie storing the username
setcookie("password", $mypassword); //Sets a cookie storing the encrypted value of the password
setcookie("typeOfUser",$type); //example variable
and the variables are passed through the URL:
header("location:http://www.example.com/logged.php?type=".$type);
inside the logged.php page I have a file called protect.php which checks whether the cookies exist and what kind of user is it.
if(isset($_COOKIE["username"])&&isset($_COOKIE["password"])){
//check if this user's cookies exist on the DB
$user = $_COOKIE["username"];
$pass = $_COOKIE["password"];
$sql="SELECT * FROM USERS WHERE Usr='".$user."' and Pass='".$pass."';";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
if($count==1){
$type = $_COOKIE["type"];
header("location:logged.php?type=".$type);
exit();
}
else{
header("location:http://www.example.com/login.php");
}
}
so if the user just types www.example.com/logged.php he/she will get the variables associated with his user, but whenever I do this I get a redirect loop on the site. (It seems to me a little bit obvious that it redirects cause each time it goes to the header("location... it restarts and at the top it checks the protect.php... but I can't figure out a way to solve this).
Note logged.php just has at the top an:
include("protect.php");
Thanks in advance!
The reason that this script loops infinitely is based in the logic:
if($count==1){
header("location:logged.php?type=".$type);
}
else{
header("location:http://www.example.com/login.php");
}
Regardless of the value of $count at this point, your script will send a location header. In other words, the browser is receiving a redirect either way, whether $count is equal to 1 or not.
if(isset($_COOKIE["username"])&&isset($_COOKIE["password"])){
In combination with this line, your loop is defined. This evaluates to true if the user has these cookies defined, which happens when they are logging in for the first time, or have already logged in. If they are logged in, their username and password must be valid, and $count will end up as 1, because they are in the database.
In short, every time the user goes to logged.php after they are logged in, this script is run because they have the appropriate cookies and they are directed, again, to "logged.php?type=."$type" (over and over again) because they are a valid user and present in the database.
To fix this, you'll want to stop header("location:logged.php?type=".$type); from running every time protect.php is run. This is the essence of your problem. You can fix this however you like, but I would do it with sessions.
Check out this tutorial to learn how to implement sessions in your logins script.
You already have three cookies: username, password, and typeOfUser. The system you have works fine, but most authentication scripts use sessions, accessible like cookies ($_COOKIE['foo']), but with the $_SESSION variable instead. The advantage to using session is that the values you store in them are not available to anyone but scripts on your server/site, to view, or to edit. In general, the less information you expose to the user, the better. If you need clarification, check out this StackOverflow post or the basic examples on the PHP website.
One more thing to point out is in your script, if(isset($_COOKIE["username"])&&isset($_COOKIE["password"])){ has no else statement. If one or both of these cookies are not defined, no code will be executed, and what I am assuming is a protected page will be displayed publicly. You may want to add an else statement, something along the lines of:
else{
header("location:http://www.example.com/login.php");
}
Hope you're able to make this functional and awesome!

How to store variables in PHP for use in different scripts?

I'm really new to programming in PHP so the problem I'm having may be an extremely simple one to solve but I cant find the solution online and I've tried a number of different methods myself so any help you can give me would be really appreciated.
The problem I'm having is that when a user logs in to the system I need their username to be stored in a variable which can be used when a different PHP script is called.
For instance, when the user first logs in to the system, the username they have entered is fetched using code similar to that seen below:
$username = ($_POST['entered_username']);
mysql_real_escape_string($username);
Where 'entered_username' is the name of the username input in the log in form within the HTML code. The problem I'm having is how to store the $username variable so it can be used in a different script. For instance when the user moves onto a page where he/she can see their own personal information which is stored in a MySQL database. Ideally I would like to use a SQL query such as the one below:
$qry = ("select Username, Password, UserType from $table where Username = '".$username."'");
However this is not possible as the variable $username would not be defined in this script. So how can I store the $username variable in order to access it again via another PHP script.
Thanks in advance for all your help and apologies if any of the information I have provided is too vague.
Most simple solution: SESSION variables.
On your login page, add this code at the top of the page:
session_start();
then set your variables like this:
$_SESSION['var_1'] = $some_val;
$_SESSION['var_2'] = $some_other_val;
you can then access them on any other php page with the session_start(); code on top.
Note however that this session data gets deleted when the user closes his/her browser. For more persistant, "long-lived" variables use $_COOKIE variables or store values in db and access the variables from there.
Useful links
How to set/delete cookies in PHP (from the Manual).
Security regarding sessions.
You need to use the $_SESSION variable. It allows you to pass data between pages.
session_start();
$username = ($_POST['entered_username']);
mysql_real_escape_string($username);
$_SESSION['username'] = $username;
then on any other page you can call it by using:
session_start();
$qry = ("select Username, Password, UserType from $table where Username = '".$_SESSION['username']."'");
Make sure that you call session_start() at the top of your page, before you have outputted any HTML to the page. Otherwise you will cause a headers error.
Use $_SESSION variables.
When a user logs in to your site store the variable in $_SESSION global variable.
session_start();
$_SESSION['user'] = $/* user */;
In another php script you can set ;
session_start();
$user = $_SESSION['user'];

session set in folders php mysql

i have this code:
$username = $_POST["username"];
$password = $_POST["password"];
if(mysql_num_rows($result80)>0)
{
$row80 = mysql_fetch_assoc($result80);
$_SESSION["loginmng"] = 1;
$_SESSION["username"] = $username;
$_SESSION["password"] = $password;
$fname = $row80["fname"];
$lname = $row80["lname"];
$userid = $row80["id"];
}
and every thing is ok because i tryed to echo the session and its work in the same page (index.php)
now i have this check:
if(($_SESSION["loginmng"]!=1)||(!isset($_SESSION["username"]))||(!isset($_SESSION["password"])))
{
header("Location: index.php");
}
when i put this into new folder:
newfolder/index.php
the check is not working right,when i have logged in , and the session is set....when i am tring to echo $_SESSION["loginmng"] and the other sessions,,its values is empty like no session setted and the header is got run ...and go to index...i have put session_start(); in the first php line too
i tryed too:
if($_SESSION["loginmng"]!=1)
{
header("Location: ../index.php");
}
and the same thing...like no session set, what may be the problem
A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.
PHP Session Variables
When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state.
A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database.
Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.
Starting a PHP Session
Before you can store user information in your PHP session, you must first start up the session.
Note: The session_start() function must appear BEFORE the <html> tag.
Maybe you forgot to add session_start(); on top of the file.
To make session start on each page you need to start the session on each page.
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.

Categories