User roles permissions PHP - php

I'm trying to create permissions for 3 diferent types of users
Normal
Admin
SuperAdmin
And I don't know how or where to start doing it because I'm still very weak with php, can someone give me an example of what to do please?
How to use Session Variable for example, I've tried a code that I found here:
<?php
$result = "SELECT * FROM customers" or die("Error: " . mysqli_error($db));
$res = $db->query($result);
while($row = mysqli_fetch_array($res)) {
$UserRoleID = $row['userRoleID'];
$_SESSION['user_role'] = $UserRoleID;
}
?>
And on another page:
<?php
if( (isset($_SESSION['user_role']) ) && (false != $_SESSION['user_role']) )
{
if( '2' == $_SESSION['user_role'] )
{
echo "<li><a href='index.php'>User</a></li>";
}
elseif ('3' == $_SESSION['user_role'] )
{
echo "<li><a href='index.php'>Admin</a></li>";
}
else
{ // error condition
// display details of invalid $_SESSION['user_role']
}
}
else
{ // error condition
// display details of missing or empty $_SESSION['user_role']
}
?>
It don't show me any error but it also don't show-me the outputs so I can't do anything

Your code does not use session_start(), so regardless of any session ID the user sees, session information will not appear to persist between requests.
Start both of your scripts with this:
<?php
session_start();

Related

PHP same Session user login

I searched but I can't find solution for me.
I have login.php file which redirect user to another page in my case theme.php?id=".$row['log_name'].".
<?php
include ('conn.php');
//Uzivatelsky vstup
$log_meno = mysqli_real_escape_string ($Conn, $_POST['login_name']);
$cmp_heslo = sha1($_POST['login_password']);
$sql = "SELECT id, cmp_heslo, log_meno FROM firmy WHERE log_meno='$log_meno'";
$result = mysqli_query($Conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row=mysqli_fetch_assoc($result)) {
if ($cmp_heslo == $row[cmp_heslo])
{
session_start();
$_SESSION['logged'] = 'yes';
echo "<script language='javascript'>window.location='comp_page/theme.php?id=".$row['log_name']."';</script>";
}
else
{
echo "<script language='javascript'>window.location='bad_login.php';</script>";
}
}
} else {
echo "0 results";
}
mysqli_close($Conn);
?>
theme.php
<?php
session_start();
if($_SESSION['logged'] != 'yes' )
die("You have to sign in first!");
?>
In MySQL I have two users
kuki with pass kuki
cuki with pass cuki
My question is when I am signed in as kuki I have in address bar:
http://localhost/comp_page/theme.php?id=kuki
But I need when I rewrite in address bar kuki to cuki to change to access denied becuase now only address bar changed but page is same. I am new to PHP.
Aside from having this in your session
$_SESSION['logged'] = 'yes';
I suggest you need to add also something like this,
$_SESSION['id'] = $row['log_name'];
and in your theme.php
session_start();
if($_SESSION['logged'] != 'yes' ) {
die("You have to sign in first!");
} else {
if ($_SESSION['id'] == $_GET['id']) {
// do somthing
} else {
echo "Access Denied!";
}
}
having this URL
http://localhost/comp_page/theme.php?id=kuki
meaning you are sending data, the id to the server with the get method. This $_GET['id'] catch that data and will have a value either kuki or cuki from the URI theme.php?id=kuki or theme.php?id=cuki.
This condition if ($_SESSION['id'] == $_GET['id']) will determine if the value of id is the same with the user store in the session.

PHP and AJAX Log in validation

I need some help troubleshooting my code that's used for Log In validation. It's a combo of AJAX and PHP.
Here's the AJAX code that's directly in the login page.
<script language="javascript">
$(document).ready(function()
{
$("#login_form").submit(function()
{
$("#msgbox").removeClass().addClass('messagebox').text('Validating....').fadeIn(1000);
$.post("/ajax_login.php",{ user_name:$('#username').val(),password:$('#password').val()
,rand:Math.random() } ,function(data)
{
if (data=='no')
{
$("#msgbox").fadeTo
(200,0.1,function()
{
$(this).html('Incorrect Username or Password.')
.addClass('messageboxerror').fadeTo(900,1);
}
);
}
else if(data=='yes')
{
$("#msgbox").fadeTo
(200,0.1,function()
{
$(this).html('Logging in.....').addClass('messageboxok').fadeTo
(900,1, function()
{
document.location='/mainpage.php';
}
);
}
);
}
else
{
$("#msgbox").fadeTo
(200,0.1,function()
{
$(this).html('User is already logged in.').
addClass('messageboxerror').fadeTo(900,1);
}
);
}
});
return false;
});
$("#password").blur(function()
{
$("#login_form").trigger('submit');
});
});
</script>
PHP CODE:
<?
//Log In credentials
if ($rehash==$dboPW && $user_name == $dboUN && $logged=='Y'){echo "alreadyLogged"; exit;}
if ($rehash==$dboPW && $user_name == $dboUN && $logged=='N')
{
echo "yes";
$_SESSION['login'] = $username;
$_SESSION['password'] = $rehash;
$loggedUpdate=mysql_query("UPDATE Users SET LOGGED='Y' WHERE username='$user_name'");
exit;
}
else
{echo "no";}
?>
To summarize this process, someone logs in and the PHP script checks
if the username and password is valid AND that the person is NOT logged in already - returns value of 'yes'
if the username and password is valid AND that the person IS logged in already - returns value of 'alreadyLogged'
Invalid username or password - returns value of 'no'
This gets passed to AJAX, which SHOULD display the correct messages based on the return values from the php script. For reference (using the above summary):
AJAX should return: Logging in...
AJAX should return: User is already logged in.
AJAX should return: Invalid Username or Password.
The problem is this: If someone logs in correctly and IS NOT already logged in, message 2 appears instead of message 1. (I think that message 1 may appear but it disappears so fast).
I think the culprit is AJAX but unfortunately I'm not as familiar with it as I am with PHP.
I think the problem is with your php code.Your ajax code looks fine
try this
if ($rehash==$dboPW && $user_name == $dboUN && $logged=='Y')
{
echo "alreadyLogged"; exit;
}
elseif ($rehash==$dboPW && $user_name == $dboUN && $logged=='N')
{
}
I think it is the php problem,it occur an error and return the error message. if ajax_login.php does not return "yes" or "no" it will show the second message, whatever it returns.
Just need modify your PHP. try this :
//Log In credentials
// check if post if (isset($_POST)) {
// must initially to use check if on loggin
session_start();
// set variable post
$username = $_POST['user_name'];
$password = $_POST['password']; // change if use sha1 or md5
$rand = $_POST['rand'];
// check query database
$query = mysql_query("SELECT * FROM Users WHERE username='$username' AND password='$password'");
$user = mysql_fetch_array($query);
$row = mysql_num_rows($query);
if ($row > 0) {
if ($user['LOGGED'] == 'Y') {
echo "yes";
$_SESSION['login'] = $username;
$_SESSION['password'] = $rehash;
$loggedUpdate = mysql_query("UPDATE Users SET LOGGED='Y' WHERE username='$user_name'");
exit;
} elseif ($user['LOGGED'] == 'N') { // you can use 'else'
echo "alreadyLogged";
exit;
}
} else {
// invalid value password and username
echo "no";
exit;
} }

php redirecting to another page

I am using the header function to locate to another page based on certain conditions. I am monitoring a mailbox and the code redirects to another page based on the sender address. All headers are working except one. If the sender does not belongs to any existing group, I wanted to redirect it to new.php. But it is not redirecting. I am unable to figure out why. Please help me.
<?php
session_start();
$server = '{server}INBOX';
$username = 'aaa#bbb.com';
$password = 'password';
require_once '../swift/lib/swift_required.php';
include('connection.php');
$connection = imap_open($server,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
$_SESSION['connection']=$connection;
$result = imap_search($connection,'UNSEEN');
if($result) {
rsort($result);
foreach($result as $email_number)
{
$header = imap_headerinfo($connection, $email_number);
$fromaddr = $header->from[0]->mailbox . "#" . $header->from[0]->host;
$query = "select * from usergroup where email='$fromaddr'";
$_SESSION['fromaddr']=$fromaddr;
$result1 = mysql_query($query) or die($query."<br/><br/>".mysql_error());
while($line=mysql_fetch_array($result1,MYSQL_ASSOC))
{
$email=$line['email'];
$group=$line['group'];
if(mysql_num_rows($result1) == 1){
if($group == 1){
header("Location: facilitator.php");
}
elseif($group == 2){
header("Location: learner.php");
}
}
elseif (mysql_num_rows($result1) == 0) {
header("Location: new.php");
}
}
}
}
elseif (!$result)
{
echo "No unread messages found";
}
?>
It appears as though you are nesting that redirection inside the while loop. Since there are no rows, the while condition mysql_fetch_array() will immediately return FALSE and skip the whole block, including the redirection you intended it to follow.
Move the test for mysql_num_rows() outside the while loop.
// Test for rows and redirect BEFORE entering the while loop.
if (mysql_num_rows($result1) === 0) {
header("Location: new.php");
// Always explicitly call exit() after a redirection header!
exit();
}
// Otherwise, there are rows so loop them.
while($line=mysql_fetch_array($result1,MYSQL_ASSOC))
{
$email=$line['email'];
$group=$line['group'];
if($group == 1){
header("Location: facilitator.php");
}
}
You actually may not need a while loop at all, depending on how many rows you are expecting to fetch. If you only expect one group per email, then forego the loop and just call $line = mysql_fetch_array() once. However, if you are expecting multiple rows but want to redirect on the first one encountered where $group == 1, then your logic works. In that case however, since you are only doing the redirection and no other action, you might as well just put that condition in your query:
// Test the group in your query in the first place.
$query = "select * from usergroup where email='$fromaddr' AND group = 1";
$result1 = mysql_query($query) or die($query."<br/><br/>".mysql_error());
if (mysql_num_rows($result1) === 0) {
// you didn't match a row, redirect to new.php
}
else {
// you had a match, redirect to facilitator.php
}
Easy one:
change:
elseif (mysql_num_rows($result1) == 0){
to:
else {
The condition in the else if is probably false - so you don't get in there and thus the redirection doesn't occur.

creating two different sessions in PHP

I am trying to create two separate sessions- one for if the user is admin and another if the user is author. $type stored type as enum (can be either author or admin). But my code is creating author session even for admin. I am new to PHP and MySQL . can somebody tell me where the error is in my code.
<?php
include("dbconnect.php");
$con= new dbconnect();
$con->connect();
//create and issue the query
$sql = "SELECT type FROM users WHERE username = '".$_POST["username"]."' AND password = PASSWORD('".$_POST["password"]."')";
$result = mysql_query($sql);
//get the number of rows in the result set; should be 1 if a match
if (mysql_num_rows($result) == 1) {
$type_num=0;
//if authorized, get the values
while ($info = mysql_fetch_array($result)) {
$type =$info['type'];
}
if($type == "admin")
{
$_SESSION['type']=1;
$u = 'welcome.php';
header('Location: '.$u);
}
else
{
$_SESSION['type']=$type_num;
$u = 'welcome.php';
header('Location: '.$u);
}
}
else {
//redirect back to loginfailed.html form if not in the table
header("Location: loginfailed.html");
exit;
}
?>
My welcome.php is as below
<?php
session_start();
?>
<html>
<body>
<h2>Welcome.</h2>
<?
if($_SESSION['type']==1){
echo "You are of the usertype Admin and your session id is ";
echo session_id();
}
else {
echo "You are of the usertype Author and your session id is ";
echo session_id();
}
?>
</body>
</html>
Thank You so much in advance.
Try to use roles for your permissions.
In general you have just one session. I mean you don't have two variables called _SESSION.
With the concept of roles you can simply check if a user has the permission to do something.
You have to call session_start() in the first part of the code, before register the var $_SESSION['type'] in the session
No your code seams fine, I think.
I don't see where you are calling the database
And what you have in there
So here is how you trouble shoot
while ($info = mysql_fetch_array($result)) {
$type =$info['type'];
echo $type . '<br />';
}
OR
echo '<pre>';
while ($info = mysql_fetch_array($result)) {
$type =$info['type'];
print_r($info);
}
echo '</pre>';
If you never see admin in there, and it must be 'admin' not Admin or ADMIN; then the problem is in your database. You don't have admin as admin defined, or spelled right.
By the way. see how nicely I formatted that. It's easier to read that way.
Coders wont look at your code if you don't do that.
Try using session_regenerate_id(); method to create different session ids.

Help on how to continue with code that verifies a registered user and updates mySQL

When a user registers, the script sends an email to verify his account. Clicking on the link, the script gets the token
$token = mysql_real_escape_string($_GET["token"]);
and what I thought to do is
if($token != '') {
mysql_query("UPDATE members SET verified = '' WHERE verified = '$token'");
}
or
if($token != '') {
$result = mysql_query("UPDATE members SET verified = '' WHERE verified = '$token'");
if($result) { }
else { }
}
What is my purpose is to echo a success or failed message on the user. When it will be success then the verified will be empty.
What is the appropriate way of doing this with my examples above?
Should I check if there is the token in the DB before updating it?
Thank you.
Your current method updates a record if it exists but does not take into account that which does not exist or match. You should run something similar to:
if($token != '') {
$result = mysql_query("SELECT COUNT(*) FROM members WHERE verified = '$token'");
while($row = mysql_fetch_row($result)) {
$records = $row[0];
}
if($records == 0) { echo 'no results'; }
elseif($records ==1) { echo 'you matched'; then update the record. }
}
edit
changed BACK to the while loop, wasn't thinking of the count returning 0 rows

Categories