PHP pages restricted access by access level - php

In MySQL table I have:
ID
username
password
level
level "admin" = access to all pages
level "user" = access only to certain pages
In auth.php page (which is included in every page).
session_start();
if(!isset($_SESSION["username"])){
header("Location: login.php");
exit();
}
In login page I have:
session_start();
// If form submitted, insert values into the database.
if (isset($_POST['username'])) {
$username = stripslashes($_REQUEST['username']); // removes backslashes
$username = mysqli_real_escape_string($conn, $username); //escapes special characters in a string
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($conn, $password);
//Checking is user existing in the database or not
$query = "SELECT * FROM `users` WHERE username='$username' and password='" . md5($password) . "'";
$result = mysqli_query($conn, $query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if ($rows == 1) {
$_SESSION['username'] = $username;
header("Location: index.php"); // Redirect user to index.php
} else {
header("Location: login.php"); // Redirect user to index.php;
}
};
How should I make two sessions, session for "admin" and session for "user", so every page would have different access level?

Try this!
$query = "SELECT * FROM `users` WHERE username='$username' and password='".md5($password)."'";
if ($result = $mysqli->query($con,$query)) {
while ($row = $result->fetch_assoc()) {
$_SESSION['username'] = $row["username"];
$_SESSION['level'] = $row["level"]);
}
$result->free();
}
Aftert that when a page requires a certain level just verify if the level is right.

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.

Multiple users at login

Please how to let every user log into his own area ?
I don't want to the users to join "thecommonplace"
I want them to be logged into their respective areas
Like for example :
anna => site.com/anna/
mike => site.com/mike/
that's what I want and I have no idea how to do it correctly
require('db.php');
session_start();
if (isset($_POST['uname']))
{
$uname = stripslashes($_REQUEST['uname']);
$uname = mysqli_real_escape_string($con,$uname);
$pwd = stripslashes($_REQUEST['pwd']);
$pwd = mysqli_real_escape_string($con,$pwd);
$query = "SELECT * FROM `users` WHERE uname='$uname' and pwd='$pwd'";
$result = mysqli_query($con, $query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows == 1)
{
$_SESSION['uname'] = $uname;
// I don't want to the users to join "thecommonplace"
// I want them to be logged into their respective areas
// Like for example :
// anna => site.com/anna/
// mike => site.com/mike/
// that's what I want and I have no idea how to do it correctly
header("Location: site.com/thecommonplace/");
}
else
{
// no such user
}
}
else // present login form
{
You almost had it! All you need to do is instead of hard coding the link, just add the $uname behind it. You can stick strings together using .
so your header line would be like this
header("Location: site.com/" . $uname);
require('db.php'); session_start();
if (isset($_POST['uname']))
{
$uname = stripslashes($_REQUEST['uname']);
$uname = mysqli_real_escape_string($con,$uname);
$pwd = stripslashes($_REQUEST['pwd']);
$pwd = mysqli_real_escape_string($con,$pwd);
$query = "SELECT * FROM `users` WHERE uname='$uname' and pwd='$pwd'";
$result = mysqli_query($con, $query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows == 1)
{
$_SESSION['uname'] = $uname;
// I don't want to the users to join "thecommonplace"
// I want them to be logged into their respective areas
// Like for example :
// anna => site.com/anna/
// mike => site.com/mike/
// that's what I want and I have no idea how to do it correctly
header("Location: site.com/" . $uname);
}
else
{
// no such user
}
}
Try This Location: site.com/$uname/
if($rows == 1)
{
$_SESSION['uname'] = $uname;
header("Location: site.com/$uname/");
}
else
{
// no such user
}

PHP session with permissions

I am having problem with the code.
It suppose to allow admin to view only admin page
and user to view user page only.
my admin still able to view user page.
below is my landing page
<?php
error_reporting(0);
include("config.php");
$host = "localhost"; //DB host
$username = "root"; //DB Username
$password = ""; //DB Password
$db_name = "hklcanet_pha"; //DB Name
$tbl_name = "users"; //Table name, where users are stored
$dbconfig = mysqli_connect($host,$username,$password,$db_name);
$username = $_POST['username']; //Get username from login form
$password = $_POST['password']; //Get password from login form
$username = stripslashes($username); //Makes string safe
$password = stripslashes($password); //Makes string safe
$username = mysqli_real_escape_string($dbconfig, $username); //Makes string safer
$password = mysqli_real_escape_string($dbconfig, $password); //Makes string safer
$sql = "SELECT * FROM $tbl_name WHERE username='$username' and password='$password'"; //SQL Query
$result = mysqli_query($dbconfig, $sql); //Executes Query
$rows = mysqli_num_rows($result); //Count rows selected (1 if a username/password combo can be found)
if($rows == 1){
session_start(); //Starts a PHP session
$_SESSION['username'] = $username; //Allows $username to be used later
header("location: interphase1.php");
$query = "SELECT * FROM $tbl_name WHERE username='$username' and password='$password'";
$result = mysqli_query($dbconfig, $query);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$permissions = $row['permissions']; //Gets the permissions of the user
$id = $row['id']; //Gets the ID of the user
}
$_SESSION['permissions'] = $permissions; //Allows $permissions to be used later
$_SESSION['id'] = $id; //Allows $id to be used later
$_SESSION['authenticated'] = 1; //Allows $id to be used later
echo("Login Succesful");//Prints success message
}
else
{
//echo("Invalid Username/Password");
}
?>
user page
<?php
session_start();
$permissions = $_SESSION['permissions'];
if($_SESSION['authenticated'] != 1)
{
echo("You must be logged in");
header("location:landing.php");
}
else
{
if($permissions < 0)
{
header("location:quicksummary.php");
echo("Your permissions are not high enough");
}
}
?>
admin page
<?php
session_start();
$permissions = $_SESSION['permissions'];
if($_SESSION['authenticated'] != 1)
{
header("location:landing.php");
echo("You must be logged in");
}
else
{
if($permissions < 1 )
{
header("location:quicksummary.php");
echo("Your permissions are not high enough");
}
}
?>
thanks and appreciate if somebody can help me on this, still new with the PHP code.

This webpage has a redirect loop PHP issue?

I am using the following codes in my login.php and index.php files.
I get the This webpage has a redirect loop error in the browser.
I know the issue is caused by the logic in the login.php file by the following code:
$existCount = mysqli_num_rows($query); // count the row nums
if ($existCount == 1) { // evaluate the count
$row = mysqli_fetch_array($query, MYSQLI_ASSOC);
$_SESSION["id"] = $row["id"];
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
header("location: http://$storeShop.mysite.com/index.php");
exit();
} else {
echo 'That information is incorrect, try again Click Here';
exit();
}
specifically this line: header("location: http://$storeShop.mysite.com/index.php");
I just do not know how I can fix this issue!
LOGIN.PHP
<?php
session_start();
ob_start();
if (isset($_SESSION["manager"])) {
/*
IF THE USER IS LOGGED IN THE CODE BELOW SENDS THEM TO THEIR OWN SUBDOMAIN NAME
WHICH IS STORED IN $_SESSION["storeShop"].
CHANGE "REST_OF_URL" TO THE VALID DOMAIN IN THE HEADER FUNCTION.
BUT DON'T REMOVE THE . (DOT)
*/
header("Location: http://$_SESSION[storeShop].mysite.com/index.php");
exit();
// END OF EDIT.
}
?>
<?php
if (isset($_POST["email"]) && isset($_POST["password"])) {
$manager = $_POST["email"]; // filter everything but numbers and letters
$password = (!empty($_POST['password'])) ? sha1($_POST['password']) : ''; // filter everything but numbers and letters
$storenameTable = $_REQUEST['storeShop'];
// Connect to the MySQL database
include "config/connect.php";
$sql = "SELECT members.id, members.email, members.password, members.randKey, members.storeShop, storename.email, storename.password, storename.randKey, storename.storeShop
FROM members
INNER JOIN storename ON members.randKey = storename.randKey
WHERE members.email = '$manager'
AND members.password = '$password'
";
$result = mysqli_query($db_conx,"SELECT storeShop FROM members WHERE email='$manager' AND password='$password'");
while($row = mysqli_fetch_array($result))
{
$email = $row["email"];
$password = $row["password"];
$storeShop = $row["storeShop"];
$_SESSION['email'] = $email;
$_SESSION['password'] = $password;
$_SESSION['storeShop'] = $storeShop;
}
// query the person
// ------- MAKE SURE PERSON EXISTS IN DATABASE ---------
$query = mysqli_query($db_conx, $sql);
if (!$query) {
die(mysqli_error($db_conx));
}
$existCount = mysqli_num_rows($query); // count the row nums
if ($existCount == 1) { // evaluate the count
$row = mysqli_fetch_array($query, MYSQLI_ASSOC);
$_SESSION["id"] = $row["id"];
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
header("location: http://$storeShop.mysite.com/index.php");
exit();
} else {
echo 'That information is incorrect, try again Click Here';
exit();
}
}
?>
INDEX.PHP
<?php
session_start();
ob_start();
if (!isset($_SESSION["manager"])) {
header("location: login");
exit();
}
/*
THE CODE BELOW COMPARES THE SUBDOMAIN TO THE USER'S STORESHOP SESSION
IF THEY DON'T MATCH IT REDIRECTS THEM TO THEIR SUBDOMAIN.
CHANGE "REST_OF_URL" TO THE VALID DOMAIN IN THE HEADER FUNCTION.
BUT DON'T REMOVE THE . (DOT)
*/
else {
$url = $_SERVER["HTTP_HOST"];
$user_subdomain = explode(".", $url);
if($_SESSION["storeShop"] != $user_subdomain[0]) {
header("Location: http://$_SESSION[storeShop].mysite.com/index.php");
}
}
ob_end_flush();
// Be sure to check that this manager SESSION value is in fact in the database
$managerID = preg_replace('#[^0-9]#i', '', $_SESSION["id"]); // filter everything but numbers and letters
$manager = $_POST["email"]; // filter everything but numbers and letters
$password = (!empty($_POST['password'])) ? sha1($_POST['password']) : ''; // filter everything but numbers and letters
$storenameTable = $_REQUEST['storeShop'];
// Run mySQL query to be sure that this person is an admin and that their password session var equals the database information
// Connect to the MySQL database
include "config/connect.php";
$sql = "SELECT members.id, members.email, members.password, members.randKey, members.storeShop, storename.email, storename.password, storename.randKey, storename.storeShop
FROM members
INNER JOIN storename ON members.randKey = storename.randKey
WHERE members.email = '$manager'
AND members.password = '$password'
"; // query the person
// ------- MAKE SURE PERSON EXISTS IN DATABASE ---------
$query = mysqli_query($db_conx, $sql);
if (!$query) {
die(mysqli_error($db_conx));
}
$result = mysqli_query($db_conx,"SELECT storeShop FROM members WHERE email='$manager' AND password='$password'");
while($row = mysqli_fetch_array($result))
{
$email = $row["email"];
$password = $row["password"];
$storeShop = $row["storeShop"];
$_SESSION['email'] = $email;
$_SESSION['password'] = $password;
$_SESSION['storeShop'] = $storeShop;
}
?>
could someone please point me in the right direction?
Thanks in advance.
You have started another session in index.php using session_start()
Remove the session_start() from index.php page and confirm if it is working fine
You're redirecting users to a different subdomain, and probably losing all your session data in the process.
Before you call session_start(), make sure your cookies are valid for the whole domain, i.e.,:
session_set_cookie_params(0, '/', '.mysite.com');
session_start();
More information here
Edit: Some other things you should look into:
(1) After the user has been redirected to "login" (header("location: login");), which of your scripts will process the next request? (Did you mean login.php?)
(2) What does login.php do when it receives a GET request (without an active session)?

Administrator permissions for login system php

<?php session_start();
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
$conn = mysqli_connect('localhost', 'smithrwg_user', 'password', 'smithrwg_database');
$_SESSION['username'] = mysqli_real_escape_string($conn, $_SESSION['username']);
$query = "SELECT password, salt
FROM tbl_mem
WHERE username = '" . $_SESSION['username'] . "';";
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) == 0) // User not found. So, redirect to login_form again.
{
header('Location: index.php');
echo "not found";
session_destroy();
}
$userData = mysqli_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $_SESSION['password']) );
if($hash != $userData['password']) // Incorrect password. So, redirect to login_form again.
{
header('Location: login.html');
}else {
// Redirect to home page after successful login.
header('Location: index.php');
$_SESSION['priv'] = $row['priv'];
}
?>
i am trying to set $_SESSION['priv'] = to the row in the mysql database table "tbl_mem" priv. but at the moment its not setting it to anything and i don't really understand how to make it do that.
$row is not defined, you probably meant to write $userData. But still this won't work - you will need to edit your query as well.
$query = "SELECT password, salt, priv FROM...";
//...
$_SESSION['priv'] = $userData['priv'];
header('Location: index.php');
It should be put in front of header() to make sure the value is really assigned

Categories