PHP array vs mysql query - php

I am working on an authorization script that checks for user name, password and access level (roles). It works fine as long as there is only one role to check.
I would like to learn how I can put the roles into an array and have the database check if any of them are present in the database for the logged in user. Right now it only check for one role.
Question: How do I construct and array for the allowed roles and then have the query check if any of them are a match?
<?php
// allowed roles
$allowedRoles = 'role1';
// needs to be like:
$allowedRoles = array('role1','role2','role3','etc.');
//------------------------------------------------------------
// instantiate sessions
//------------------------------------------------------------
if (!isset($_SESSION)) {
session_start();
}
//------------------------------------------------------------
// define auth variables
//------------------------------------------------------------
$first_pass = 0; // sessions
$second_pass = 0; // password
$third_pass = 0; // role
//------------------------------------------------------------
// check if sessions exist and are valid
//------------------------------------------------------------
if(!empty($_SESSION['UserName']) && !empty($_SESSION['Password']) && !empty($_SESSION['LoggedIn']) && $_SESSION['LoggedIn'] == 1)
{
// FIRST PASS OK!
$first_pass = 1;
echo 'PASSED: 1st ';
}
if($first_pass == 1)
{
//------------------------------------------------------------
// include db connection
//------------------------------------------------------------
require_once('../../connections/mysql.php');
// set variables
$session_un = $_SESSION['UserName'];
$session_pw = $_SESSION['Password'];
// DB QUERY: check username SESSION credential against db
// ------------------------------------------------------------------
$session_auth = mysqli_query($conn, "SELECT UserId, UserName, Password FROM users WHERE UserName = '$session_un' AND IsApproved = 1 AND IsLockedOut = 0 LIMIT 1")
or die($dataaccess_error);
// ------------------------------------------------------------------
if(mysqli_num_rows($session_auth) == 1)
{
$row = mysqli_fetch_array($session_auth);
$auth_UserId = $row['UserId'];
$auth_Password = sha1(sha1($row['Password']));
// if passwords match
if($auth_Password == $session_pw)
{
// SECOND PASS OK!
$second_pass = 1;
echo 'PASSED: 2nd ';
if($second_pass == 1)
{
// DB QUERY: check ROLE credentials in db
// ------------------------------------------------------------------
$auth_roles = mysqli_query($conn, "SELECT UserId, RoleId, RoleName FROM users_in_roles WHERE UserId IN ($auth_UserId) AND RoleName IN ('$allowedRoles')")
or die($dataaccess_error);
// ------------------------------------------------------------------
if(mysqli_num_rows($auth_roles) > 0)
{
// THIRD PASS OK!
$third_pass = 1;
echo 'PASSED: 3rd ';
}
else
{
// redirect back to login page
header('Location: ../../login.php');
}
}
}
}
}
?>
Thank you!

You're almost there. You just need to convert your list of allowed roles from an array into a string:
$allowedRoles = "'" . implode("', '", $allowedRoles) . "'";
$auth_roles = mysqli_query($conn, "SELECT UserId, RoleId, RoleName FROM users_in_roles WHERE UserId IN ($auth_UserId) AND RoleName IN ($allowedRoles)")

Related

Notice: Undefined variable: email in /Applications/XAMPP/xamppfiles/htdocs/menthor/login.php on line 16

When signing into to the app with username, the email is not used hence the following error is throw and vice versa "Notice: Undefined index: email in /Applications/XAMPP/xamppfiles/htdocs/menthor/login.php on line 16"
I've tried putting the lines that were generating the error in conditions but those efforts proved futile
Login.php file(parts relevant to the error)
// STEP 1. Receive data / info paassed to current file
if ((empty($_REQUEST['username']) || empty($_REQUEST['password'])) && (empty($_REQUEST['email']) || empty($_REQUEST['password']))) {
$return['status'] = '400';
$return['message'] = 'Missing requird information';
echo json_encode($return);
return;
}
// securing received info / data from hackers or injections
$email = htmlentities($_REQUEST['email']);
$username = htmlentities($_REQUEST['username']);
$password = htmlentities($_REQUEST['password']);
// STEP 2. Establish connection with the server
require('secure/access.php');
$access = new access('localhost' , 'root', '' , 'menthor');
$access->connect();
// STEP 3. Check existence of the user. Try to fetch the user with the same email address
// STEP 3. Check availability of the login/user information
$username_aval = $access->selectUser_Username($username);
$email_aval = $access->selectUser_Email($email);
//$return = array();
// user is found
if ($username_aval) {
// Get encrypted password and salt from the server for validation
$encryptedPassword = $username_aval['password'];
$salt = $username_aval['salt'];
if ($encryptedPassword == sha1($password . $salt)) {
$return['status'] = '200';
$return['message'] = 'Successfully Logged In';
$return['id'] = $username_aval['id'];
$return['username'] = $username_aval['username'];
$return['email'] = $username_aval['email'];
$return['fullName'] = $username_aval['fullName'];
$return['lastName'] = $username_aval['lastName'];
$return['birthday'] = $username_aval['birthday'];
$return['gender'] = $username_aval['gender'];
$return['cover'] = $username_aval['cover'];
$return['ava'] = $username_aval['ava'];
$return['bio'] = $username_aval['bio'];
$return['allow_follow'] = $username_aval['allow_follow'];
} else {
// In event that encrypted password and salt does not match
$return['status'] = '201';
$return['message'] = 'Password do not match';
}
} else if ($email_aval) {
// Get encrypted password and salt from the server for validation
$encryptedPassword = $email_aval['password'];
$salt = $email_aval['salt'];
if ($encryptedPassword == sha1($password . $salt)) {
$return['status'] = '200';
$return['message'] = 'Successfully Logged In';
$return['id'] = $email_aval['id'];
$return['username'] = $email_aval['username'];
$return['email'] = $email_aval['email'];
$return['fullName'] = $email_aval['fullName'];
$return['lastName'] = $email_aval['lastName'];
$return['birthday'] = $email_aval['birthday'];
$return['gender'] = $email_aval['gender'];
$return['cover'] = $email_aval['cover'];
$return['ava'] = $email_aval['ava'];
$return['bio'] = $email_aval['bio'];
$return['allow_follow'] = $email_aval['allow_follow'];
} else {
// In event that encrypted password and salt does not match
$return['status'] = '202';
$return['message'] = 'Password do not match';
}
}else {
// In event that user is not found
$return['status'] = '403';
$return['message'] = 'User was not found';
}
// stop connection with server
$access->disconnect();
// pass info as JSON
echo json_encode($return);
Access.php file(parts relevant to error)
Will try to select any value in the database based on received Email
public function selectUser_Email($email) {
// array to store full user related information with the logic: key=>Value
$returnArray = array();
// SQL Language / Commande to be sent to the server
// SELECT * FROM users WHERE email='rondell#gmail.com'
$sql = "SELECT * FROM users WHERE email='" . $email . "'";
// executing query via already established connection with the server
$result = $this->conn->query($sql);
// result isn't zero and it has least 1 row / value / result
if ($result != null && (mysqli_num_rows($result)) >= 1) {
// converting to JSON
$row = $result->fetch_array(MYSQLI_ASSOC);
// assign fetched row to ReturnArray
if (!empty($row)) {
$returnArray = $row;
}
}
// throw back returnArray
return $returnArray;
}
// Will try to select any value in the database based on received Email
public function selectUser_Username($username) {
// array to store full user related information with the logic: key=>Value
$returnArray = array();
// SQL Language / Commande to be sent to the server
// SELECT * FROM users WHERE username='rondell'
$sql = "SELECT * FROM users WHERE username='" . $username . "'";
// executing query via already established connection with the server
$result = $this->conn->query($sql);
// result isn't zero and it has least 1 row / value / result
if ($result != null && (mysqli_num_rows($result)) >= 1) {
// converting to JSON
$row = $result->fetch_array(MYSQLI_ASSOC);
// assign fetched row to ReturnArray
if (!empty($row)) {
$returnArray = $row;
}
}
// throw back returnArray
return $returnArray;
}
Current results when logging in via web server
Notice: Undefined index: email in /Applications/XAMPP/xamppfiles/htdocs/menthor/login.php on line 16
{"status":"200","message":"Successfully Logged In","id":"44","username":"rondell","email":"rondell#gmail.com","fullName":"rondell","lastName":"","birthday":"","gender":"","cover":"","ava":"","bio":"","allow_follow":"1"}
Expected Results
{"status":"200","message":"Successfully Logged In","id":"44","username":"rondell","email":"rondell#gmail.com","fullName":"rondell","lastName":"","birthday":"","gender":"","cover":"","ava":"","bio":"","allow_follow":"1"}
use email as object or you can dump the request and see what is happening
Turns out the solution was pretty simple came to be after a bit of hard think... I just needed to simply create two login.php files... One dedicated to the users signing in with username and password and the other for users signing in with email and password...Cheers

Checked the query, database, table names, column names, etc. Still have no idea why this error occurred

The error that I occurred:
Fatal error: Call to a member function bind_param() on boolean in C:\wamp64\www\APU\SDP\reg-list-function.php on line 82
I'm writing a php script where the Admins are able to approve the registration of the user. I've checked through the formats of my database, column names, and even query, and still I've no idea why this error pops out. Any help or suggestions will be appreciated!
<?php
// we will only start the session with session_start() IF the session isn"t started yet //
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
?>
<?php
// including the conn.php to establish connection with database //
include "conn.php";
?>
<?php
// Begin of the function: Registration List's Verification Form: Registration //
// First we check the form has submitted or not //
if (isset($_POST['submit-list-reg'])) {
// If it is, then we will retreive data from the input forms //
$regid = $_POST["regid"];
$reg_acccode = mysqli_real_escape_string($con, $_POST['reg-acccode']);
$reg_pw = mysqli_real_escape_string($con, $_POST['reg-pw']);
// Taking the current time //
date_default_timezone_set("Etc/GMT-8");
$now = date("Y-m-d H:i:s");
// Variable to store Error Message //
$error = '';
// Alphanumeric Generator //
function random_strings($length_of_string) {
// String of all alphanumeric character
$str_result = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
// Shufle the $str_result and returns substring
// of specified length
return substr(str_shuffle($str_result), 0, $length_of_string);
}
// Sorting out the query related to the function //
// Verify the user is an admin or not //
$VERFYADMIN = "SELECT * FROM user
WHERE status = 2 AND active = 1 AND account_code = '".md5($reg_acccode)."' AND password = '".md5($reg_pw)."'";
$VERFYADMINQ = mysqli_query($con, $VERFYADMIN);
//***BEGIN OF PROCESS***//
if (mysqli_num_rows($VERFYADMINQ) < 1) {
// if the admin is not verified, then inform the user and send him back to admin panel //
echo "<script>alert('ALERT: Information unable to be verified. Please try again.');";
echo "window.location.href='admin_panel.html';</script>";
exit(0);
} else {
// begin the process of registration //
while (list($key,$val) = #each ($regid)) {
// Now to verify the user's legitimacy //
// Take the user's vercode into variable first //
$USERVERCODE = "SELECT * FROM registration_list
WHERE registration_id = $val AND verified = 0";
$USERVERCODEQ = mysqli_query($con, $USERVERCODE);
if (mysqli_num_rows($USERVERCODEQ) < 1) {
// if we are unable to retrieve the data of the registering user then something must gone wrong //
echo "<script>alert('WARNING: Unable to retrieve the data. Please try again.');";
echo "</script>";
} else {
while ($row = mysqli_fetch_array($USERVERCODEQ)) {
$vercode = $row["verification_code"];
}
// since we got the value of the vercode then we start to define the query //
$VERCODE = "SELECT * FROM verification_code WHERE verification_code = $vercode AND code_active = 1";
$VERCODEQ = mysqli_query($con, $VERCODE);
if (mysqli_num_rows($VERCODEQ) < 1) {
// if we are unable to retrieve the data of the registering user then something must gone wrong //
echo "<script>alert('WARNING: Unable to retrieve the info of VERCODE. Please try again.');";
echo "</script>";
} else {
while ($row = mysqli_fetch_array($VERCODEQ)) {
$status = $row["code_status"];
}
// we will first insert the user main information into the database: i.e. password, username, etc. //
$account_code = random_strings(8);
$APPROVE = "INSERT INTO user (username, password, email, account_id, account_code, active, status, registered_date, verification_code)
SELECT username, password, email, account_id, '".md5($account_code)."', 1, $status, $now, verification_code
FROM registration_list
WHERE registration_id = ?";
$stmt = $con->prepare($APPROVE);
$stmt->bind_param("i", $val); // Problem around here //
$stmt->execute();
if (($stmt->error) == FALSE) {
I expect the process will be no issue at all as I've checked everything and nothing seems wrong to me.
Reformatting your code to make it more legible and easier to understand, we now have:
<?php
// we will only start the session with session_start() IF the session isn"t started yet //
if (session_status() == PHP_SESSION_NONE)
{
session_start();
}
?>
<?php
// including the conn.php to establish connection with database //
include "conn.php";
?>
<?php
// Begin of the function: Registration List's Verification Form: Registration //
// First we check the form has submitted or not //
if (isset($_POST['submit-list-reg']))
{
// If it is, then we will retreive data from the input forms //
$regid = $_POST["regid"];
$reg_acccode = mysqli_real_escape_string($con, $_POST['reg-acccode']);
$reg_pw = mysqli_real_escape_string($con, $_POST['reg-pw']);
// Taking the current time //
date_default_timezone_set("Etc/GMT-8");
$now = date("Y-m-d H:i:s");
// Variable to store Error Message //
$error = '';
// Alphanumeric Generator //
function random_strings($length_of_string)
{
// String of all alphanumeric character
$str_result = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
// Shufle the $str_result and returns substring
// of specified length
return substr(str_shuffle($str_result), 0, $length_of_string);
}
// Sorting out the query related to the function //
// Verify the user is an admin or not //
$VERFYADMIN = "SELECT * FROM user
WHERE status = 2 AND active = 1 AND account_code = '".md5($reg_acccode)."' AND password = '".md5($reg_pw)."'";
$VERFYADMINQ = mysqli_query($con, $VERFYADMIN);
//***BEGIN OF PROCESS***//
if (mysqli_num_rows($VERFYADMINQ) < 1)
{
// if the admin is not verified, then inform the user and send him back to admin panel //
echo "<script>alert('ALERT: Information unable to be verified. Please try again.');";
echo "window.location.href='admin_panel.html';</script>";
exit(0);
}
else
{
// begin the process of registration //
while(list($key,$val) = #each ($regid))
{
// Now to verify the user's legitimacy //
// Take the user's vercode into variable first //
$USERVERCODE = "SELECT * FROM registration_list WHERE registration_id = $val AND verified = 0";
$USERVERCODEQ = mysqli_query($con, $USERVERCODE);
if (mysqli_num_rows($USERVERCODEQ) < 1)
{
// if we are unable to retrieve the data of the registering user then something must gone wrong //
echo "<script>alert('WARNING: Unable to retrieve the data. Please try again.');";
echo "</script>";
}
else
{
while ($row = mysqli_fetch_array($USERVERCODEQ))
{
$vercode = $row["verification_code"];
}
// since we got the value of the vercode then we start to define the query //
$VERCODE = "SELECT * FROM verification_code WHERE verification_code = $vercode AND code_active = 1";
$VERCODEQ = mysqli_query($con, $VERCODE);
if (mysqli_num_rows($VERCODEQ) < 1)
{
// if we are unable to retrieve the data of the registering user then something must gone wrong //
echo "<script>alert('WARNING: Unable to retrieve the info of VERCODE. Please try again.');";
echo "</script>";
}
else
{
while ($row = mysqli_fetch_array($VERCODEQ))
{
$status = $row["code_status"];
}
// we will first insert the user main information into the database: i.e. password, username, etc. //
$account_code = random_strings(8);
$APPROVE = "INSERT INTO user (username, password, email, account_id, account_code, active, status, registered_date, verification_code)
SELECT username, password, email, account_id, '".md5($account_code)."', 1, $status, $now, verification_code
FROM registration_list
WHERE registration_id = ?";
$stmt = $con->prepare($APPROVE);
$stmt->bind_param("i", $val); // Problem around here //
$stmt->execute();
if (($stmt->error) == FALSE)
{
In here are several things that I wouldn't personally do. As has been mentioned, using variables supplied by user input, even MD5 ones, directly in SQL queries should be best avoided.
The line "while(list($key,$val) = #each ($regid))", which sets the $val variable has an ampersand to suppress any error messages, this in turn could be causing you issues further down. It's best not to suppress these messages, but to find out why they are occurring, this could be the cause of a non numeric value being passed to your "bind_param" function. I'd also use single quotes instead of double quotes with the function as well.
Solved after I changed the variables that contained string value with this format -> ' " . $variable . " ' .

How to save table data in session

I have problem in little project,
how can I save table data in session?
<?php
session_start();
include 'connect.php';
if (isset($_POST["email"]))
{
$email = $_POST["email"];
$password = $_POST["password"];
$r=mysql_query("SELECT * FROM user_login WHERE `uemail` ='".$email."' AND `upass` = '".$password."'");
$s = $_POST["userid"];
$n=mysql_query("SELECT * FROM user_data WHERE `userid` ='".$s."'");
$q=mysql_fetch_assoc($n);
$_SESSION["name"]=$q["nfname"];
$k=mysql_num_rows($r);
if ($k>0)
{
header("location:user/index.php");
}
else
header("location:login.php");
}
?>
this code not working !! :(
please help !
You probably just missed the
session_start();
But here is the dildo (deal tho) xD
Your Login script is not secure, try this at the top of your index.php or whatever rootfile you have.
<?php
session_start();
function _login($email, $password) {
$sql = "SELECT * FROM user_login
WHERE MD5(uemail) ='".md5(mysql_real_escape_string($email))."'
AND MD5(upass) = '".md5(mysql_real_escape_string($password))."'";
$qry = mysql_query($sql);
if(mysql_num_rows($qry) > 0) {
// user with that login found!
$sql = "UPDATE user_login SET uip = '".$_SERVER['REMOTE_ADDR']."', usession = '".session_id()."'";
mysql_query($sql);
return true;
} else {
return false;
}
}
function _loginCheck() {
$sql = "SELECT * FROM user_login WHERE uip = '".$_SERVER['REMOTE_ADDR']."' AND MD5(usession) = '".md5(session_id())."'";
$qry = mysql_query($sql);
if(mysql_num_rows($qry) > 0) {
// user is logged in
$GLOBALS['user'] = mysql_fetch_object($qry);
$GLOBALS['user']->login = true;
} else {
// user is not logged in
$GLOBALS['user'] = (object) array('login' => false);
}
}
if(isset($_POST['login'])) {
if(_login($_POST["email"], $_POST["password"])) {
// login was successfull
} else {
// login failed
}
}
_loginCheck(); // checkes every Page, if the user is logged in or if not
if($GLOBALS['user']->login === true) {
// this user is logged in :D
}
?>
Ok, I'll bite. First 13ruce1337, and Marc B are right. There is a lot more wrong with this than not being able to get your data into your session.
Using PDO ( as 13ruce1337 links you too ) is a must. If you want to keep using the same style of mysql functions start reading up on how. Marc B points out that session_start(); before any html output is required for sessions to work.
As for your code, you got along ways to go before it is ready for use but here is an example to get you started
if (isset($_POST["email"])) {
//mysql_ functions are being deprecated you can instead use
//mysqli_ functions read up at http://se1.php.net/mysqli
/* Manage your post data. Clean it up, etc dont just use $_POST data */
foreach($_POST as $key =>$val) {
$$key = mysqli_real_escape_string($link,$val);
/* ... filter your data ... */
}
if ($_POST["select"] == "user"){
$r = mysqli_query($link,"SELECT * FROM user_login WHERE `uemail` ='$email' AND `upass` = '$password'");
/* you probably meant to do something with this query? so do it*/
$n = mysqli_query($link,"SELECT * FROM user_data WHERE userid ='$userid'");
//$r=mysql_fetch_assoc($n); <- this overrides your user_login query
$t = mysqli_fetch_array($n);
$_SESSION["name"] = $t['nfname'];
/* ... whatever else you have going on */

Check permissions for user

I am trying to make permission page thy will check if user have full access than some option allow to this person.I have table named users there i have 5 columns name user_id , username , password , email , permission
respectively .so now i am showing what i have done.
permissions.php
<?php
include('db.php');
$result=mysql_query("SELECT permission,user_id FROM users");
while($test = mysql_fetch_array($result))
{
$test['user_id'];
$test['permission'];
}
?>
For example mysql result on first row: $test['user_id'] = 1 and $test['permission'] = full .
Session result: $_SESSION['user_name'] = admin
So how can i check if this user id have permission full than do some think.
I am new on php sorry for my bad explanation.
<?php
include('db.php');
$result = mysql_query("SELECT permission,user_id FROM users WHERE username = '$_SESSION[user_name]'");
if(mysql_num_rows($result)){
$data = mysql_fetch_row($result); // fetch first row of result, we don't need a loop, as username should be unique
$permission = $data['permision'];
$user_id = $data['user_id'];
}else{
echo "Username not found.";
}
?>
if user have full permission, store in session full permission
while($test = mysql_fetch_array($result))
{
$_SESSION['permission'] = $test['permission'];
}
check if user have full permission
if($_SESSION['permission'] == full){
//do shomething
}
<?php
include('db.php'); // though you should look in to "PDO"
// default permission--disallowed
$allowed = false;
// get the permission for the current user (based on the username within
// your session variable). also make sure to sanitize anything that's being
// placed within a query to the database.
$query = sprintf("SELECT permission "
."FROM users "
."WHERE username = '%s'",
mysql_real_escape_string($_SESSION['user_name']));
$result = mysql_query($query);
while (($test = mysql_fetch_array($result)) !== false){
// we found the username, now check their access
$allowed = $test['permission'] == 'full';
}
// if ($allowed){
// super secret area
// } else {
// get out of here
// }

Header redirects not working as expected

I have the following function which retrives the currently logged in users' username and finds out their access level from the database (either 'requested','user', or 'admin')
function fetchAccess()
{
global $con;
$username = $_SESSION['username'];
$q = "SELECT access FROM users WHERE username = '$username' LIMIT 1";
$result = mysql_query($q, $con);
$row = mysql_fetch_assoc($result);
$access = $row['access'];
if(isset($_SESSION['username']))
{
if($access == 'user')
{
return 1; // Returns 1 if access level is user
}
elseif($access == 'admin')
{
return 2; // Returns 2 if access level is admin
}
elseif($access == 'requested')
{
return 3; // Returns 3 if access level is requested
}
}
}
When I am checking whether the user is an admin using the follow code, this works correctly.
/* Redirects user if access level does not equal admin */
$result = fetchAccess();
if($result != 2)
{
header("location:index.php");
}
However when I check to see whether the access is 'requested' - this following is NOT working correctly.
<?php
/* Redirects user if access level does is 'requested' */
$result = fetchAccess();
if($result == 3)
{
header("location:redirect.php");
}
?>
Does anyone know why this is?
You can do this:
function fetchAccess()
{
global $con;
$username = $_SESSION['username'];
$q = "SELECT access FROM users WHERE username = '$username' LIMIT 1";
$result = mysql_query($q, $con);
$row = mysql_fetch_assoc($result);
global $access
$access = $row['access'];
}
then:
global $access
if($access != admin){
header("location:redirect.php");
}
Have you verified that $result actually equal to 3? it may very well be that in the first instance $result == "" which is != 2 so it is not working at all. Try debugging it by including a header like:
<?php
$result = fetchAccess();
header("X-my-result: [$result]");
if ( $result == 3 ) {
header("Location: redirect.php");
}
?>
and see what you get back for value of $result in the headers.
do an echo statement to see what is return in the $result variable. btw, i'm not sure if your logic in your first redirect statement is to encompass both 'user' and 'requested', but those users will be redirected to index.php

Categories