Storing session variables in PHP loaded from mysqli - php

I am trying to store session variables upon a login form, so that I can reference them on further pages. The echo of $row[level] is successful, but none of the SESSION variables.
session_start();
if (isset($_POST['username']) and isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT firstname, level, username FROM `roster` WHERE username ='$username' and password ='$password'";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
if ($result->num_rows > 0) {
//while($row = $result->fetch_assoc()) {
//echo $row[level];
//header('location:begin.php');}
while ($row = $result->fetch()) {
$_SESSION['level'] = $row[level];
$_SESSION['firstname'] = $row[firstname];}
}}
I had also tried this, which successfully works for storing the username as a session variable but not the level variable.
session_start();
if (isset($_POST['username']) and isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT firstname, level, username FROM `roster` WHERE username ='$username' and password ='$password'";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
$count = mysqli_num_rows($result);
if ($count == 1){
$_SESSION['username'] = $username;
}else{$fmsg = "Invalid Login Credentials.";
}
}if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
$level = $_SESSION['level'];
header ('location: begin.php');
Thanks for your help!

Use quotes here
$_SESSION['level'] = $row["level"];
$_SESSION['firstname'] = $row["firstname"];
Be sure about looping and overwriting variable value, otherwise use array.

Related

how to add user role in php

I tried to redirect my users and admin to some certain pages but my php code is redirecting both the admin and users to the same page
if (isset($_POST['Login'])) {
$username = $_POST['username'];
$password = $_POST['surname'];
$password_hash = md5($password);
$role;
if (!empty($username) && (!empty($password)))
{
$query = "SELECT 'id' FROM users WHERE 'staffno' = '$username' AND 'password'='$password_hash'";
$run = mysqli_query($conn, $query);
if ($run) {
$sql = "SELECT users.role FROM users";
$result = mysqli_query($conn, $sql);
$user = mysqli_fetch_array( $result);
//$_SESSION['admin'] = $user['admin'];
$_SESSION['role'] = "admin";
if((isset($_SESSION['role']) && $_SESSION['role'] == "admin")){
header("location: Upload.php");
}else{
header("location: Home.php");
}
}
Try
if($run){
$_SESSION['role'] = $user['role'];
If($user['role'] == 'admin'){ //admin page}else{//the other page}
}
Also try limiting your result on your first query by adding
LIMIT 0, 1
Your code is now even short
Try to use this:
$_SESSION['role'] = $user['database-role-column-name'];
I'm assuming, you are session started at the top. Since, you have hardcoded $_SESSION['role'] variable
$_SESSION['role'] = "admin";
And, this always be true
if((isset($_SESSION['role']) && $_SESSION['role'] == "admin")){
You need to use instead
$_SESSION['role'] = $user['role'];
You need to stored dynamic user role in the session
$_SESSION['role'] = "admin";
change to
$_SESSION['role'] = $user['Your_User_Role_coulmn_name'];
This script $user = mysqli_fetch_array( $result); will return all information about selected user, so if you are storing user role in the same table then you can store the user role value in the session. In this way your if statement will be functional as per requirement.
Also for using session you need add session_start() before using $_SESSION.
Please check the example
session_start();
if (isset($_POST['Login'])) {
$username = $_POST['username'];
$password = $_POST['surname'];
$password_hash = md5($password);
$role;
if (!empty($username) && (!empty($password)))
{
$query = "SELECT `id` FROM users WHERE `staffno` = '$username' AND `password`='$password_hash'";
$run = mysqli_query($conn, $query);
if ($run) {
$sql = "SELECT users.role FROM users";
$result = mysqli_query($conn, $sql);
$user = mysqli_fetch_array( $result);
$_SESSION['role'] = "admin"; // this approach will be always same
$_SESSION['role'] = $user['Your_User_Role_coulmn_name']; // you need to store dynamic user role into the session
if((isset($_SESSION['role']) && $_SESSION['role'] == "admin")){
header("location: Upload.php");
}else{
header("location: Home.php");
}
}
}
}
Can you start by changing $password = $_POST['surname']; to $password = $_POST['password']; and see if it solve your issue.

Cannot get password_verify to work (PHP, MYSQL)

I've set up password_hash in my registration script. Can't figure out how to use password_verify correctly to log into my website.
Screenshot of DB: https://i.imgur.com/hWjRiXN.png
Login Code (says "incorrect login, even when the password is correct):
<?php
require 'db_connect.php';
if (isset($_POST['username']) and isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM `member` WHERE username='$username'";
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
$count = mysqli_num_rows($result);
if (password_verify($_POST['password'],$hashword))
{
echo "Correct login";
}
else
{
echo "incorrect login";
}
}
?>
Registration Code(Works great, no issues with DB connection either):
<?php
require 'db_connect.php';
$email = $_POST['email'];
$username = $_POST['username'];
$password1 = $_POST['password1'];
$password2 = $_POST['password2'];
if($password1 != $password2)
header('Location: registration.html');
if(strlen($username) > 25)
header('Location: registration.html');
$hashword = password_hash($password,PASSWORD_DEFAULT);
$query = "INSERT INTO member ( username, password, email)
VALUES ( '$username', '$hashword', '$email');";
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
mysql_close();
header('Location: login.html');
?>
From your code, it looks like you are not checking the $_POST['password'] with the correct hashword which was inserted into the database.
The variable $hashword will have nothing and hence password_verify fails.
Fetch the value of password which was stored in the database and store it in $hashword variable then use it in the password_verify function for it to work as intended.
Example
$row = mysqli_fetch_assoc($result);
$hashword = $row['password'];
Usage
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
$count = mysqli_num_rows($result);
$row = mysqli_fetch_assoc($result);
$hashword = $row['password'];
if (password_verify($_POST['password'],$hashword))
{
echo "Correct login";
}
else
{
echo "incorrect login";
}

php admin and user account doesn't work

I have a login form. I have in my table of the database two records: admin and user. If you login if admin you must go to admin_area.php. this is not working, he always log in if user.
If you login if user this works.
The first part of the script is not working and don't run.
Can someone help me?
thanks in advance.
<?php
//first part: this is not working
session_start();
//if (isset($_POST['submit'])) {
$a_username = $_POST ['username'];
$a_password = md5( $_POST ['password']);
if($a_username == "admin" && $a_password=="intel")
{
include 'connect.php';
$sqli = "SELECT * FROM users WHERE username='$a_username' AND password='$a_password' ";
$numrows = mysqli_query($link, $sqli) or die(mysqli_error());
$username = 'username';
$password = 'password';
//Add some stripslashes
$username = stripslashes($username);
$password = stripslashes($password);
//Check if username and password is good, if it is it will start session
if ($username == $a_username && $password == $a_password)
{
$_SESSION['username'] = 'true';
$_SESSION['username'] = $username;
//Redirect to admin page
header("Location: admin_area.php");exit();
}
}
//second part: this works
$username = $_POST ['username'];
$password = md5( $_POST ['password']);
if($username&&$password)
{
include 'connect.php';
$query = "SELECT * FROM users WHERE username='$username' AND password='$password' ";
$numrows = mysqli_query($link, $query) or die(mysqli_error());
if ($numrows != 0)
{
/
while ($row = mysqli_fetch_assoc ($numrows))
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if ($username==$dbusername&&$password==$dbpassword)
{
echo "you are log in <a href='user.php'>click here for contine</a>, after 4 seconds"; header('Refresh: 4;url=user.php');
$_SESSION ['username'] = $username;
}
else
echo "<h3>incorrect password, <a href='index.php'>click here</a></h3>";
}
else
die ("text");
}
else
die ("text");
//}
?>
$a_password = md5( $_POST ['password']);
if($a_username == "admin" && $a_password=="intel")
This condition is not valid, because
$a_password = md5( $_POST ['password'])
is first converted to md5 format and then checked $a_password=="intel"
$a_password is now in md5 format and intel is normal string. For this first try to match normal $a_password like
$a_password = $_POST ['password']
and write your variable into your condition as like
$a_password = md5( $_POST ['password'])

php user login from database won't login

Hi i've made a login script, but it won't log me in, and keeps telling me incorrect match. Here's my code:
include_once("dbConnect.php");
// Set the posted data from the form into local variables
$usname = strip_tags($_POST['username']);
$paswd = strip_tags($_POST['password']);
$usname = mysqli_real_escape_string($dbCon, $usname);
$paswd = mysqli_real_escape_string($dbCon, $paswd);
$sql = "SELECT * FROM user WHERE username = '$usname' AND usertype = '1' LIMIT 1";
$query = mysqli_query($dbCon, $sql);
$row = mysqli_fetch_row($query);
$uid = $row[0];
$dbUsname = $row['username'];
$dbPassword = $row['password'];
// Check if the username and the password they entered was correct
if ($usname == $dbUsname && $paswd == $dbPassword) {
// Set session
$_SESSION['username'] = $usname;
$_SESSION['id'] = $uid;
// Now direct to users feed
header("Location: user.php");
} else {
echo "<h2>Oops that username or password combination was incorrect.
<br /> Please try again.</h2>";
}
The username is admin, and passcode is PPsleep1 and the usertype is 1, you can try yourself: http://daltyapps.com/daltyapps/portfolio/paypal/log/index.php
With the current situation, I can suggest you following fixes in the code:
<?php
include_once("dbConnect.php");
// Set the posted data from the form into local variables
$usname = strip_tags($_POST['username']);
$paswd = strip_tags($_POST['password']);
$usname = mysqli_real_escape_string($dbCon, $usname);
$paswd = mysqli_real_escape_string($dbCon, $paswd);
// use both username and password to retrieve records from table
$sql = "SELECT * FROM user WHERE username = '$usname' AND password = '$paswd' AND usertype = '1'";
$query = mysqli_query($dbCon, $sql);
if($query) // check if query runs properly or is having any error
{
if(mysqli_num_rows($query) == 1) // check if ony one user with 'USERNAME - PASSWORD' pair exists in database
{
$row = mysqli_fetch_row($query);
$uid = $row[0];
$dbUsname = $row[INDEX_OF_USERNAME_FIELD];
// Set session
$_SESSION['username'] = $usname;
$_SESSION['id'] = $uid;
// Now direct to users feed
header("Location: user.php");
}
else
{
echo "<h2>Oops that username or password combination was incorrect.
<br /> Please try again.</h2>";
}
}
else
{
echo "Error in query ".mysqli_error($dbCon);
}
?>
Use below code,
include_once("dbConnect.php");
// Set the posted data from the form into local variables
$usname = strip_tags($_POST['username']);
$paswd = strip_tags($_POST['password']);
$usname = mysqli_real_escape_string($dbCon, $usname);
$paswd = mysqli_real_escape_string($dbCon, $paswd);
$sql = "SELECT * FROM user WHERE username = '$usname' AND usertype = '1' LIMIT 1";
$query = mysqli_query($dbCon, $sql);
$row = mysqli_fetch_array($query); /*comment - have replace row with array*/
$uid = $row[0];
$dbUsname = $row['username'];
$dbPassword = $row['password'];
// Check if the username and the password they entered was correct
if ($usname == $dbUsname && $paswd == $dbPassword) {
// Set session
$_SESSION['username'] = $usname;
$_SESSION['id'] = $uid;
// Now direct to users feed
header("Location: user.php");
} else {
echo "<h2>Oops that username or password combination was incorrect.
<br /> Please try again.</h2>";
}
Second option to use,
include_once("dbConnect.php");
// Set the posted data from the form into local variables
$usname = strip_tags($_POST['username']);
$paswd = strip_tags($_POST['password']);
$usname = mysqli_real_escape_string($dbCon, $usname);
$paswd = mysqli_real_escape_string($dbCon, $paswd);
$sql = "SELECT * FROM user WHERE username = '$usname' AND usertype = '1' LIMIT 1";
$query = mysqli_query($dbCon, $sql);
$row = mysqli_fetch_row($query);
$uid = $row[0];
$dbUsname = $row[1]; /*comment - if column username after column id in table */
$dbPassword = $row[2]; /*comment - if column password after column username in table*/
// Check if the username and the password they entered was correct
if ($usname == $dbUsname && $paswd == $dbPassword) {
// Set session
$_SESSION['username'] = $usname;
$_SESSION['id'] = $uid;
// Now direct to users feed
header("Location: user.php");
} else {
echo "<h2>Oops that username or password combination was incorrect.
<br /> Please try again.</h2>";
}

Save $_SESSION on JQUERY $.POST

I have an HTML page in which I use Jquery .post() to post the forms into one big php file. I thought that this way I'll be able to save the username in a $_SESSION.
I have a login form that stores the username into a session, but then, when I try to display the php file (using .load()) in a different html page (linked to by the login one) I have no session variable set.
When I did a little debugging I found out the session is lost only if it's created in the if(isset($_POST['username'})) part of the page.
<?php
session_start();
include_once("connect.php");
$username = $_SESSION['username'];
//check if username is in session
if(isset($_SESSION['username'])) {
$username = $_SESSION['username'];
echo "<script>$(document).ready(function(){location.replace('index.html#home')});</script>";
}else{
?>
<div id="part_login">
<?php
//if not, check login
if(isset($_POST['username']) and isset($_POST['password'])){
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = md5($_POST['password']);
$result = mysqli_query($conn, "SELECT * FROM users WHERE username='$username' AND password='$password' AND active='1' LIMIT 1") or die(mysqli_error($conn));
$count = mysqli_num_rows($result);
if ($count == 1){
$_SESSION['username'] = $username;
$result = mysqli_query($conn, " SELECT * FROM `users` WHERE username = '$username'");
while($row = mysqli_fetch_array($result)) {
$oldlogin = $row['lastlogin'];
}
echo "<script>$(document).ready(function(){location.replace('index.html#home')});</script>";
}else{
echo "<div class='ui-btn'>Invalid Login Credentials</div>";
}
}
}
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
$result = mysqli_query($conn, " SELECT * FROM `users` WHERE username = '$username'");
while($row = mysqli_fetch_array($result)) {
$oldlogin = $row['lastlogin'];
}
$query = mysqli_query($conn, "UPDATE `users` SET lastlogin=now() WHERE username='$username' LIMIT 1");
}else{
}
?>
</div>
<div id="part_user">
<?
echo $username . " " . $oldlogin;
?>
</div>

Categories