0

I would like to know how to check if user is logged in and if user privilege is correct using procedural style. I am new to PHP. The code I am trying to use is the follow but it does not work at all I don´t know why:

Here is the login script

   <?php 
    session_start();
    $local=$_POST["local"];
    $locales = array('001', '002', '003', '004', '005', '006', '007', '008', '009', '010');
    if (in_array($local, $locales)){include ''.$local.'/enlace.php';} 
    else {header('Location: index.php?error=7');}
    $locatario=mysqli_real_escape_string($database,$_POST['personal']);
    $seguridad=mysqli_real_escape_string($database,$_POST['clave']);
    if (empty($locatario) || empty($seguridad)| empty($local)){header('Location: index.php?error=1');exit();}
    if (preg_match("/[^A-Za-z0-9]/", $locatario)){header('Location: index.php?error=2');exit();}
    if (preg_match("/[^A-Za-z0-9]/", $seguridad)){header('Location: index.php?error=3');exit();}
    $locatarios = mysqli_query($database, "SELECT * FROM `locatarios` WHERE locatario='$locatario' LIMIT 1");
    if(mysqli_num_rows($locatarios)==0){header('Location: index.php?error=4');exit;}
    $informacion=mysqli_fetch_array($locatarios,MYSQL_ASSOC);
    $criptologia=hash('sha256',$informacion['codificacion'].hash('sha256',$seguridad));
    if($criptologia!=$informacion['seguridad']){header('Location: index.php?error=5');exit;}
    $_SESSION['identificacion']=$informacion['locatario'];
    if ($informacion['privilegio']=="VENTAS"){header('Location: '.$local.'/ventas/index.php?funcion=inicio');exit();}
    else if($informacion['privilegio']=="ADMINISTRACION"){header('Location: '.$local.'/administracion/index.php?funcion=inicio');exit();}
    else if($informacion['privilegio']=="BODEGA"){header('Location: '.$local.'/bodega/index.php?funcion=inicio');exit();}
    else if($informacion['privilegio']=="SOPORTE"){header('Location: '.$local.'/soporte/index.php?funcion=inicio');exit();}
    else if($informacion['privilegio']=="PROPIETARIO"){header('Location: '.$local.'/propietario/index.php?funcion=inicio');exit();}
    else if($informacion['privilegio']=="CLIENTES"){header('Location: '.$local.'/clientes/index.php?funcion=inicio');exit();}
    else {header('Location: index.php?error=6');exit();}
    ?>

After user is logged in we check for login session and privilege but I am getting error

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, array given in /home/local/public_html/001/propietario/index.php on line 10

<?php
session_start();
$identificar = $_SESSION['identificacion'];
include 'sistema/enlace.php';
$locatarios = mysqli_query($database, "SELECT * FROM `locatarios` WHERE locatario='$identificar' LIMIT 1");
$controlar = mysqli_fetch_array($locatarios, MYSQLI_ASSOC);
$privilegio = $controlar["privilegio"];
if ($privilegio=='PROPIETARIO'){} 
else {header('Location: /no-privs.php');exit();}
while($locatario = mysqli_fetch_array($controlar))
{
?>
<html>
<head>
<title>ADMIN ZONE</title>
</head>
<body>
WELCOME <?php echo $locatario[privilegio]?>, YOU ARE ADMIN ON THIS SITE</div>
</body>
</html>
<?php
}
?>
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
  • Are you unsetting the PHP Session each time you test whether user is Admin or not? You may need to close browser window or use something like Firebug to destroy the session var between your test rounds. – Adam T Apr 15 '15 at 16:02
  • Yeah I am unsetting the settion with logout.php also trying with 5 different browsers and 3 PC even phone and tablet – quieroprivacidad Apr 15 '15 at 16:04
  • `$_SESSION['session_name']` first needs to be assigned to something, I.e.: `$_SESSION['session_name'] = "John";`. You're not doing anything with it really, unless it's coming from another page. If so, then just do `WELCOME ` along with an `isset()` – Funk Forty Niner Apr 15 '15 at 16:04
  • I would try putting the HTML output code for Admin within the conditional if ($privilege=='ADMIN'){} - Also, your code checks, yes, but then as long as there's a true evaluation in the while, it means that any user can see it. Maybe redirect isn't redirecting? – Adam T Apr 15 '15 at 16:05
  • It is comming from login.php – quieroprivacidad Apr 15 '15 at 16:06
  • You're using the wrong variable `$control = mysqli_fetch_array($locatarios, MYSQLI_ASSOC);` - `$locatarios` should be `$members`. If that fixes it, I'll post it as an answer. Let me know before the vampires move into my comment; how many times it's happened already. – Funk Forty Niner Apr 15 '15 at 16:12
  • It feels like the script it not correct but I am new to PHP – quieroprivacidad Apr 15 '15 at 16:13
  • You are correct I will try it – quieroprivacidad Apr 15 '15 at 16:14
  • 1
    @Fred-ii- Nice one, mentioning the vampires. – Adam T Apr 15 '15 at 16:19
  • @AdamT Already got bitten twice today. That "once bitten twice shy" thing, doesn't go off too well lol - and that's not just me, but other guys too that truly like to help. We help out the OP and do all the work, and no word from others just waiting in the back of their coffins.... for the big feast. – Funk Forty Niner Apr 15 '15 at 16:22
  • @quieroprivacidad So, where are we at here; still having problems? Also try `if( isset($_SESSION['session_name']) && $privilege=='ADMIN' ) {...}` - ADMIN might be case-sensitive too, so check your column. – Funk Forty Niner Apr 15 '15 at 16:24
  • I had to edit the login sript too so in some minutes I will upload and test – quieroprivacidad Apr 15 '15 at 16:31
  • Ok. Let me know if any of my comments worked or not. – Funk Forty Niner Apr 15 '15 at 16:31
  • got Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, array given in line 10 – quieroprivacidad Apr 15 '15 at 16:38
  • Add `or die(mysqli_error($database))` to `mysqli_query()`. Your query may be failing because the session array isn't set or empty. – Funk Forty Niner Apr 15 '15 at 16:41
  • Did this $database = mysqli_connect ($server, $user, $pass, $db) or die(mysqli_error($database)) got same error – quieroprivacidad Apr 15 '15 at 16:45
  • I will edit the question with the real code – quieroprivacidad Apr 15 '15 at 16:47
  • Now the question is edited and I show the real code. It is in spanish but only variable names – quieroprivacidad Apr 15 '15 at 16:50
  • `while($username = mysqli_fetch_array($control))` needs to be `while($username = mysqli_fetch_array($members))` that should fix it, as I tested your code just now. – Funk Forty Niner Apr 15 '15 at 16:50
  • Edited with your code and it give me the error in line 10 of index.php – quieroprivacidad Apr 15 '15 at 16:56
  • 1
    You are assigning an array to $controlar ($controlar = mysqli_fetch_array(..)) and then doing a mysql_fetch_array() again to it. That's why it gives you an error. – ricardgf Apr 15 '15 at 17:18
  • So, did you resolve this? If so, how? You can post your own answer to let everyone know. – Funk Forty Niner Apr 15 '15 at 17:37
  • Still not working Fred getting the error – quieroprivacidad Apr 15 '15 at 17:47
  • I have posted an answer/solution for you below. Please go through it carefully. – Funk Forty Niner Apr 15 '15 at 18:14
  • 1
    **WARNING**: When using `mysqli` you should be using parameterized queries and [`bind_param`](http://php.net/manual/en/mysqli-stmt.bind-param.php) to add user data to your query. **DO NOT** use string interpolation to accomplish this because you will create severe [SQL injection bugs](http://bobby-tables.com/). **NEVER** put `$_POST` data directly into a query. – tadman Apr 15 '15 at 18:47

1 Answers1

0

Ok. Well there's no sense in re-explaining all this, it's already been done in comments.

Nota: You will need to modify the session array and how it's being populated as well as some other variables if required.

However, you should first check to see if the session array is set as outlined in comments already.

This I used in conjunction with your originally posted code, so you will have to modiy it to suit your actual code in your language.

Tested/working on my own server:

<?php
session_start();

$DB_HOST = 'xxx';
$DB_USER = 'xxx';
$DB_PASS = 'xxx';
$DB_NAME = 'xxx';

$database = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($database->connect_errno > 0) {
  die('Connection failed [' . $database->connect_error . ']');
}

// here we check the user session name
$_SESSION['session_name'] = "John";

$identify_session = $_SESSION['session_name'];

$members = "SELECT * FROM `members` WHERE username='$identify_session' LIMIT 1";

$query = mysqli_query($database, $members);

$control = mysqli_fetch_array($query, MYSQLI_ASSOC);

// we check users privilege example ADMIN or MOD or USER
$privilege = $control["privileges"];

echo $privilege;

// because we are in admin page we show page or redirect him if no privilege
if ($privilege=='ADMIN')

    {

    // echo "You're in!";

    } 


else {

header('Location: /get_out.php');

exit();

}

 if ($result = $database->query($members)) {


    while ($locatario = $result->fetch_assoc())

{
?>
<html>
<head>
<title>ADMIN ZONE</title>
</head>
<body>
WELCOME <?php echo $locatario[username]?>, YOU ARE ADMIN ON THIS SITE</div>
</body>
</html>
<?php
} // brace for while loop

} // brace for if ($result = $database->query($members))
?>

Footnotes:

However, doing it this way leaves you open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.

Community
  • 1
  • 1
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141