Check role of user logged in (PHP) - 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
}

Related

Validate admin is logged in php

I have a php script that generates an RSS feed, but I only want it to be accessible by admins. I currently use this method
if($_SESSION['isAdmin'] != true) {
$_SESSION['sessionErrors'][] = "Sorry, you are not allowed access the page 'Update RSS Feed'";
header("Location: /");
}
It works on other pages but for some reason it not working here.
I want it the page to, validate the user is an admin ($_SESSION['isAdmin] == true), execute the script updating the RSS file, the redirect back to the regular admin page.
Here is a basic skeleton of the page. I removed all the stuff that doesn't matter
<?php
if($_SESSION['isAdmin'] != true) {
$_SESSION['sessionErrors'][] = "Sorry, you are not allowed access the page 'Update RSS Feed'";
header("Location: /");
}
$file = fopen('rss.xml', "w") or die("Unable to open file");
try {
// Connect to db
$conn = new PDO("mysql:host=" . SERVERNAME . ";" . "dbname=" . DBNAME, USERNAME, PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $conn->query('SELECT * FROM * ORDER BY upload_date DESC ');
$result = $query->fetchAll(PDO::FETCH_OBJ);
$rssfeed = 'This gets set based on what the db returns';
} catch (PDOException $e) {
echo $e->getMessage();
}
fwrite($file, $rssfeed);
fclose($file);
header("Location: /admin.php");
In my testing, when I'm not logged in, it still executes the script (generating the rss.xml file), then redirects me back to the admin page. Which I'm not logged in so that redirects me back to / with the error saying I'm not allowed to access admin.php
You need to exit after sending the Location header.
The header function just adds a header to the result that will be sent eventually. As you don't exit, all the code that follows is still executed, and the output from that code is sent to the client, together with the Location header.
Add exit() to the end of the location header redirect. This will prevent the code after that from being executed.
<?php
if($_SESSION['isAdmin'] != true) {
$_SESSION['sessionErrors'][] = "Sorry, you are not allowed access the page 'Update RSS Feed'";
header("Location: /");
exit(); // It will stop here.
}
// The rest of the code
.........
After reading the comments I realized I never started the session with session_start();🤦
However I also added exit(); to the end of the redirect because that seems like good practice I guess.
Still learning a lot about php so any advice you guys give me is much appreciated. Thanks for the help!!

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");
}

PHP sessions not working as expected

So I am creating an application (new -ish to sessions) and have been trying to create a simple error handling statement using sessions.
To simplify things, let me describe the basics.
User enters query on page 1
User presses submit
Page 2 is loaded to check the value of the query
If the query is set, it is run and the result is displayed on page 3
If it is empty however, an error is caught, set and the user is redirected back to page 1
What I care about is the last step as I cannot get it to work for some reason.
Here is the code pertaining to the error:
Page 1s relevant code:
<?php
session_start();
$ERROR = $_SESSION['error'];
if($ERROR) {
echo $ERROR;
}
?>
And on page 2:
<?
session_start();
---------------- And as we go down the file a bit ----------------
if(trim($getQuery == "")){
$ERROR = "no search criteria entered";
$_SESSION['error'] = $ERROR;
if(!isset($_SESSION['error'])) {
die("the session error was not set for some reason");
}
$url = "localhost:8000/mysite"; //index.php is page 1 in this case so I just redirect to the parent directory as index is loaded by default obviously in that case
header("Location:" . $url);
}
?>
$getQuery is the value captured in the query box on page 1 and sent via the post method to page 2 as you may assume naturally.
But when I enter nothing in the query box and then send the query, the page refreshes (as it should when page 2 realises that the query is empty and header location reloads the page) but no error is shown, which it should considering I check on page 2 that it is set.
Any ideas?
Cheers,
-- SD
You have a typo in if(trim($getQuery == "")) { ... } it should be if(trim($getQuery) == "") { ... }, since you only want to trim the $getQuery variable, and not the whole condition. If you change this, then it will work.
Here's a minimum working example
<?php // 1.php
session_start();
$ERROR = $_SESSION['error'];
if($ERROR) {
echo $ERROR;
}
?>
<?php // 2.php
$getQuery = ""; // This is empty so it will redirect to 1 and show error message
session_start();
if(trim($getQuery) == ""){
$ERROR = "no search criteria entered";
$_SESSION['error'] = $ERROR;
if(!isset($_SESSION['error'])) {
die("the session error was not set for some reason");
}
$url = "1.php"; //index.php is page 1 in this case so I just redirect to the parent directory as index is loaded by default obviously in that case
header("Location:" . $url);
}
?>
Sometimes the browser redirect (your header("Location")) can be quicker than the server.
Just before the redirect you should put
session_write_close()
Just to make sure the session is written for next time.

Check redirect source

I have a form to edit an entry, after the user presses the submit button it executes the includes/edit.php?id=XXX script and then redirects using the header('Location: ../index.php'); to the index page where all the entries are being displayed.
On the index page, I want to create a condition:
if the index page is accessed via a redirect from the edit.php?id=XXX page, then show a success message to notify the user that the edit was succesfull.
How should this condition look like?
<?php
require_once('includes/session.php');
require_once('includes/config.php');
if(!isset($_SESSION['login'])){ //if login in session is not set
header("Location: http://www.domain.com/app/login.php");
}
$query = ("SELECT * FROM archive ORDER by id DESC");
$result = mysqli_query($link, $query) or die (mysqli_error());
/*if (condition){
//show success message
}*/
?>
You should take a look at this var :
$_SERVER['HTTP_REFERER'];
As it will return the page from where you come before this one:
So you could just do :
if($_SERVER['HTTP_REFERER'] == "edit.php?id=XXX"){
// your code here
}
you can simply try this :
if(isset($_GET['id']) && !empty($_GET['id']))
{
// your success message
}
If you set a $_SESSION variable with messages you can then display all messages and clear the list afterwards.
Adding a message:
if ( ! isset($_SESSION['messages']) ) {
# initialize messages
$_SESSION['messages'] = [];
}
# Add a new message:
$_SESSION['messages'][] = 'Something was a success!';
Reading messages:
# If there are messages not displayed
if ( isset($_SESSION['messages']) && is_array($_SESSION['messages']) ) {
foreach ( $_SESSION['messages'] as $message ) {
echo $message . '<br>';
}
# Clear messages
unset( $_SESSION['messages'] );
}
The suggested 'HTTP_REFERER' can be manipulated and browsers are not required to send it.
I would suggest to redirect immediately and not execute more code after the location header is set:
if(!isset($_SESSION['login'])){ //if login in session is not set
header("Location: http://www.domain.com/app/login.php");
exit();
}
If $_SESSION['login'] is not set: redirect and exit.
You might consider the rest of the code as one big "else" (= if $_SESSION['login'] is set).
To answer the question from comments: without the exit, the code below will be executed .. and doing that query is not really necessary. Thats why its better to end the program flow by adding an exit. Referencing: Why I have to call 'exit' after redirection through header('Location..') in PHP?
And for the condition you could use $_SERVER['HTTP_REFERER'] or $_GET['id'] to check the page you are coming from. Just compare the strings or parts of them.

Protecting webpage via authentication

I am developing a portal with PHP, and would need to implement a simple PHP authentication system which restricts access to certain pages depending on the credentials of the user.
I have a function CheckAuth() which takes a paramater (Integer). Ie, my database has five authorization levels 1-5. If I call CheckAuth(3) this will return true if the user has authorization level 3 or above. My code right now reads:
if(!CheckAuth(3) {
die("Sorry, we were unable to deliver the requested content.");
}
The problem with this solution is that it will break the page's layout as other elements such as the page's footer will not be displayed.
What is the best way of conditionally displaying only a portion of the page?
Thanks in advance!
Dario
function CheckAuth() {
require("config.php");
//User ain't been logged in?
if(!isset($_SESSION["login"])) {
return 0;
}
//Alright user is logged in, lets check the level...
//1 = User, 2 = OP (or Admin)
$query = "SELECT * FROM delegations WHERE id=" . $_SESSION["login"];
$results = mysqli_query($con, $query);
while($row = mysqli_fetch_array($results)) {
return $row["Level"];
}
}
Solution is not to use die() but to render another version of page.
if (!CheckAuth(3)) {
// render error page
} else {
// render normal page
}
You shouldnt ask for if (!CheckAuth(3)) you should better go the way of if (CheckAuth(3)) and display the Page data if the user has the permission to view the content, if not redirect him to a 403 page something like this
if(CheckAuth(3))
{
//display page content
}
function CheckAuth($permissionLevel)
{
require("config.php");
//User ain't been logged in?
if(!isset($_SESSION["login"])) {
return 0;
}
//Alright user is logged in, lets check the level...
//1 = User, 2 = OP (or Admin)
$query = "SELECT * FROM delegations WHERE id=" . $_SESSION["login"];
$results = mysqli_query($con, $query);
while($row = mysqli_fetch_array($results)) {
if($row["Level"] == $permissionLevel)
{
return true;
}
}
header("Status: 403 Forbidden");
header("Location: /403.html");
exit;
}

Categories