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
// }
Related
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 . " ' .
i am making a code where the system checks if you are an 'Admin' or a 'SuperAdmin'.
i cant seem to make it loop everything to check if 'SuperAdmin' is in the 'user_type'
$sql = "SELECT * from users";
$result = mysqli_query($con,$sql);
while ($row2 = mysqli_fetch_array($result)) {
if ($row2['user_type'] != "SuperAdmin") {
echo "<script>window.alert('You do not have administrative
priviledges for this page!');
location.href='../admin_page.php';</script>";
} else {
}
}
window.alert("You do not have administrative priviledges for this page!"); location.href="../admin_page.php";';
} else {
}
?>
I believe you want to check if the current use is an "Admin" or a "SuperAdmin". In that case, you need to get the row for the current user using the UserID that you get after authenticating the user. Change your query and php code to something like:
$UserId = 111; //This is the user id from database you get on authenticating the user: e.g. 111.
$sql = "SELECT * from users WHERE UserId = ". $UserId;
$result = mysqli_query($con,$sql); //This should retrieve a single row, with details for the specific user.
while ($row2 = mysqli_fetch_array($result)) {
if !(($row2['user_type'] == "SuperAdmin")||($row2['user_type'] == "Admin")){
echo "<script>window.alert('You do not have administrative
priviledges for this page!');
location.href='../admin_page.php';</script>";
} else {
//Code to be executed if the user is an admin or a super admin
}
}
enter image description hereenter image description hereI have contructed this 2 files. The REGISTER works properly but the LOGIN seems doesn't find the user 'cause always I receive"echo 2". Any suggestion. Thanks
LOGIN:
<?php
require("config.inc.php");
if (!empty($_POST)) {
$user = $_POST['User'];
$mail = $_POST['Mail'];
$token = $_POST['Token'];
$pass = $_POST['Pass'];
$query_user = "SELECT * FROM Proteos WHERE User = '$user'";
$query_pass = "SELECT * FROM Proteos WHERE Pass = '$pass'";
$query_execuser = mysql_query($query_user) or die(mysql_error());
$query_execupass = mysql_query($query_pass) or die(mysql_error());
$rowsuser = mysql_num_rows($query_execuser);
$rowspass = mysql_num_rows($query_execpass);
if ($rowuser==0){
echo 2;
}else if ($rowuser==$rowpass){
echo 3;
}else if ($rowuser!=$rowpass) {
echo 4;
}
mysqli_close($con)
?>
<?php
}
?>
first,correct your query select query, that is use one instead of two
e.g $query_user = "SELECT * FROM Proteos WHERE user = '$user' and pass='$pass'"
second, make a practice of using lowercase while querying db e.g pass instead of Pass, user instead of User, some servers may not work property on this,
third, call your new form, I cant see it here, as in I only see echo for values, instead something like header("location : you_file.php");
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 */
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)")