Block access based on SESSION - php

I am working on a user based website. So, I have different sections for different users. I want that if the session username is "Rock", he shouldn't be able to access other user's profile say "Gray".
So,
if $_session['username']=="rock"
{
//BLOCK ACCESS TO OTHER FILES IN FOLDER PLACED IN DIRECTORY
}
How do I do that?
Thank you

If you have multiple users you can't hard-code this type of thing.
Assuming your using a database...
// Comes from database
$username = $row['username'];
// Check session
if ($username !== $_SESSION['username']) {
header("Location: /access/denied/page/");
exit();
}

On gray's page you could have:
if($_SESSION['username'] != 'gray'){
header('Location: http://www.goal.com/');
exit;
}
If you want to allow certain people to access gray's page you could have an array with the people that can access it...
$allowed = array('bob', 'james');
if(!in_array($_SESSION['username'], $allowed)){
header('Location: http://www.goal.com/');
exit;
}
Or the other way around, if you only want to deny certain people access you could have.
$blocked = array('rock', 'pop');
if(in_array($_SESSION['username'], $blocked)){
header('Location: http://www.goal.com/');
exit;
}

Related

Prevent User from accessing admin.php

I'm having a problem preventing regular users from accessing my admin.php page.
I've set in the database it so that users have a type (it's a boolean so either 0 = admin or 1 = normal user)
At the top of my admin.php page I have
<?php
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
}
elseif(!isset($_SESSION['type']) && $_SESSION['type'] !== 0) {
header('Location: profile.php');
exit;
}
?>
I originally had the last piece of code as:
elseif(!isset($_SESSION['type']) || $_SESSION['type'] !== 0) {
header('Location: profile.php');
exit;
but this would prevent all users, both admin or normal, from accessing the admin page. I'm not sure how to proceed.
Edit: I'm a novice at PHP and still a student so I'm not 100% familiar with PHP.
Correct code is:
// Check if the user is logged in
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] == true){ // if login
if(!isset($_SESSION['type']) && $_SESSION['type'] == 0){ //if admin (type == 0)
header('Location: profile.php');
}
else{ //if not admin (type !== 0)
header('send somewhere else');
}
}
else { // else not login
header('Location: login.php');
exit;
}
Since you're a novice at PHP, what I'm going to recommend is not an answer to fix your code (I don't see any obvious problem with it), but instead how to set up your development environment so that you can easily see what the problem is yourself.
There are two main options:
1.) (Best option) Setup Xdebug and an IDE so that you can debug your code in real time, line by line
2.) Use echo to output information to the page
Option #1
This is the best option, and I highly recommend you learn how to debug PHP line by line, as soon as you can. Xdebug is the most popular debugger for PHP; you'll need to set that up and install it. Then you'll need an IDE that supports debugging. I recommend PHPStorm if you have the funds, or Sublime Text if you need a free option.
Option #2
Instead of having your code redirect, have it output information, like this:
$loggedIn = isset($_SESSION["loggedin"]);
echo $loggedIn;
$type = $_SESSION['type'];
echo $type;
This is kind of the "poor mans" debugging. It allows you to see printed to the page, what the values of variable are. Once you know what the values are, you'll easily be able to figure out why your code isn't working. You can even then do things like this:
elseif(!isset($_SESSION['type']) && $_SESSION['type'] !== 0) {
echo "this will take you to profile.php";
}

Sessions in php do not load profiles, php + mysql

I need to be able to orientate with a php code that communicates with data from a mysql database, this file is called "validate.php". Its main functions are to verify that there are no empty fields at the time of login, and assign a profile if a user has value 1 and another profile when the value is 0 in the records of the table "users"
The idea is that "validate.php" check the user and direct it to a page according to their profile, but I can not do that.
My code is:
<?php
require('access_db.php');
session_start();
if(isset($_POST['send'])) { // We verify that the form data has been sent
//We verify that the user_name and the user_pass fields are not empty
if(empty($_POST['user_name']) || empty($_POST['user_pass'])) {
echo"
<script>
alert('Please enter your username and password correctly ');
location.replace('login.php');
</script>
";
}else {
//"Clean" the form fields of possible malicious code
$user_name = mysqli_real_escape_string($link,trim($_POST['user_name']));
$user_pass = mysqli_real_escape_string($link,trim($_POST['user_pass']));
// We verify that the data entered in the form match those of the DB
$query=mysqli_query($link,"select user_id,user_name,user_admin FROM users WHERE user_name='".$user_name."' and user_pass ='".$user_pass."'");
$row = mysqli_fetch_array($query);
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row["user_name"];
$_SESSION['user_admin'] = $row["user_admin"];
if($_SESSION['user_admin']==1){
echo "dashboard.php";
}else{
echo "dashboard2.php";
}
{
}
}else{
header("Location: login.php");
}?>
My main problem is here:
if($_SESSION['user_admin']==1){
echo "dashboard.php";
}else{
echo "dashboard2.php";
}
When I login with my admin user in my page "login.php" you should check the information and go to a page according to your profile, only appears in the browser "http://localhost/proyect/validate.php" and the text "dashboard" on the page, But, if I write in the browser "http://localhost/proyect/dashboard.php" load the page with all the information.
I do not know what I'm doing wrong.
Someone can help me, I'll be very grateful, I've been on this for days.
Thanks.
Don't print, try this instead:
if($_SESSION['user_admin']==1){
header('location:dashboard.php');
exit;
}else{
header('location:dashboard2.php');
exit;
}
Thanks for the suggestion Magnus Eriksson
you need to redirect not echo out the contents of the php file
and also do check for { as there are extra ones
if($_SESSION['user_admin']==1){
header("Location: dashboard.php");
}else{
header("Location: dashboard2.php");
}

Check role of user logged in (PHP)

first, I have searched for a question that is the same with mine, unfortunately I can't understand the answers. It says use Auth, etc... bla bla bla. I only know basics so far.
So here is my question: how to check the user currently logged in and its role?
I thought I could do it so easily, actually I did, but the user of the site I'm building should only be one. lol. I have two columns named session and membership. Anyway, my code is written below (It is definitely wrong, I just realized it this 2AM in the morning. It would 100% work if the user of the side is again only one.
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
header("Location: http://localhost/se/");
}
//if(!empty($_SESSION['user']) )
else
{
//This following codes are for checking the session in DB
$query = "
SELECT
id,
password,
emailAddress,
membership
FROM memberlist
WHERE
session = :var_val
";
// The parameter values
$query_params = array(
':var_val' => 'True'
);
try
{
// Execute the query against the database
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
$row = $stmt->fetch();
if ( $row['membership'] == 'Officer' || $row['membership'] == 'Member' )
{
header("Location: http://localhost/memberdir/index.php");
}
}
If a user's membership == 1, then go to admin directory.
else go to members directory.
Please help :(
To start a user session:
session_start();
To add parameters to that session:
$_SESSION['parameter'] = $parameter;
To get that parameter:
$getParameter = $_SESSION['parameter'];
So make sure you put session_start(); before any output to the page (before you print anything):
if ( $row['membership'] == 'Officer' || $row['membership'] == 'Member' )
{
session_start();
$_SESSION['membership'] = $row['membership'];
include('memberdir/index.php');
//or header("Location: http://localhost/memberdir/index.php");
}
So in your member file that you show a particular user (or only one user, doesn't make a difference), you check that the session parameter exists and what to do with it:
if (isset($_SESSION['membership'])) {
//membership parameter is set
if($_SESSION['membership'] == 'Officer') {
echo "Hey, your membership is Officer, here is your page";
} else if ($_SESSION['membership'] == 'Member') {
echo "Hey your membership is Member, here is your page";
}
}
This should help you understand the basics and you can go from there.
when the user login success you can do like this:
if(login success)
{
$_SESSION['user']=array('id'=>$id,
'emailAddress'=>$emailAddress,
'membership'=>$membership);//the three values are selected from database when login in
}else
{
// do some thing
}
then when you check the user ,you can use:
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
header("Location: http://localhost/se/");
}else
{
//get user info from session
}

How do i send a user to another page using header if session is empty?

I am making a form over a few pages that will send me an email at the end but i don’t want people going to other pages if they have not inputted their IGN (in game name) so i have tried to put it into a session. My problem is checking the session as i can’t get it to send the user back to the main page if the session is empty here is my code so far.
<?php session_start();
$_SESSION['IGN']=$_POST['IGN'];
if ($_SESSION['IGN']="") {
header('Location: Index.php');
}
?>
Is it that im checking the session wrong? Can you take a look and help me please :-)
Yes, you need to do:
if ( $_SESSION['IGN'] == "" ) { // here you need to use "==" instead of "="
header('Location: Index.php');
}
Read the manual how to compare.
Also you can check in such way:
if (isset($_SESSION['IGN']) && !empty($_SESSION['IGN'])) {
header('Location: Index.php');
}
try this:
<?php session_start();
$_SESSION['IGN']=$_POST['IGN'];
if ($_SESSION['IGN']=="" || is_null($_SESSION['IGN'])) {
header('Location: Index.php');
}
?>

restrict users with sessions

I am looking to add pages on my site that only people with a certan rank will be able to see while others will be kicked to a different page. What would be a simple way of doing this?
This is what I have right now.
<?php session_start();
$rank=$_SESSION['rank'];
$loggedinusername=$_SESSION['loggedinusername'];
$loggedinuseremail=$_SESSION['loggedinuseremail'];
?>
Thanks
For single allowed rank
if ($rank != 'allowed_rank') {
header('Location: some_other_page.php');
exit;
}
For multiplpe allowed ranks
if (!in_array($rank, array('allowed_rank1', 'allowed_rank2'))) {
header('Location: some_other_page.php');
exit;
}
<?php
session_start();
if ($_SESSION['rank'] > 1) // or whatever your minimum rank is
{
header('Location: highrankpage.php');
}
else
{
header('Location: lowrankpage.php');
}
exit();
?>
You'll want to include this code on every page that you want to protect.

Categories