'PHP sessions (user/admin) user levels

I am only new to php, a few weeks self teaching myself and making various projects to learn how to do things...

I am currently making a basic project consisting of... index (login page) register home (user level) admin (admin level) logout dbconnect

I have a column in my db called userlevel with 0 as default and i will change to 1 for admin accounts....

at the moment any user that logs in can access the home.php page because the session variable is 'user' so as long as any user is logged in they go to home.php or else return to index if login is not valid.... like i said i am very new to php and only began learning about sessions today so its all a bit overwhelming... basically i just pasted the same page from home to admin to begin editing the session details so that it will only allow users with userlevel 1 to access admin else back to index.... my code for the relevant pages is as follows.....

index.php (login page)

<?php
	ob_start();
	session_start();

	require_once 'dbconnect.php';


	
	// it will never let you open index(login) page if session is set
	if ( isset($_SESSION['user'])!="" ) {
		header("Location: home.php");
		exit;
	}
	
	$error = false;
	
	if( isset($_POST['btn-login']) ) {	
		
		// prevent sql injections/ clear user invalid inputs
		$email = trim($_POST['email']);
		$email = strip_tags($email);
		$email = htmlspecialchars($email);
		
		$pass = trim($_POST['pass']);
		$pass = strip_tags($pass);
		$pass = htmlspecialchars($pass);
		// prevent sql injections / clear user invalid inputs
		
		if(empty($email)){
			$error = true;
			$emailError = "Please enter your email address.";
		} else if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
			$error = true;
			$emailError = "Please enter valid email address.";
		}
		
		if(empty($pass)){
			$error = true;
			$passError = "Please enter your password.";
		}
		
		// if there's no error, continue to login
		if (!$error) {
			
			$password = hash('sha256', $pass); // password hashing using SHA256
		
			$res=mysql_query("SELECT id, fname, pass FROM project WHERE email='$email'");
			$row=mysql_fetch_array($res);
			$count = mysql_num_rows($res); // if uname/pass correct it returns must be 1 row
			
			if( $count == 1 && $row['pass']==$password ) {
				$_SESSION['user'] = $row['id'];	
				header("Location: home.php");
			} else {
				$errMSG = "Incorrect Credentials, Try again...";
			}

				
		}
		
	}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Sign In</title>
</head>
<body>


<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">


<input type="email" name="email" placeholder="Enter Your Email" value="<?php echo $email; ?>" maxlength="40" />
<?php echo $emailError; ?><br>

<br>

<input type="password" name="pass" placeholder="Enter Your Password" maxlength="15" />
<?php echo $passError; ?><br>

<br>

<button type="submit" name="btn-login">Sign In</button><br>


<br>
<br>
<a href="register.php">Register</a> <a href="index.php">Sign in</a> <a href="admin.php">Admin</a>
<br>
<?php
if ( isset($errMSG) ) {

?>
 <?php echo $errMSG; ?>

<?php
}
?>


</body>
</html>
<?php ob_end_flush(); ?>

home.php

<?php
	ob_start();
	session_start();
	require_once 'dbconnect.php';

	
	// if session is not set this will redirect to login page
	if( !isset($_SESSION['user']) ) {
		header("Location: index.php");
		exit;
	}
	// select loggedin users detail
	$res=mysql_query("SELECT * FROM project WHERE id=".$_SESSION['user']);
	$userRow=mysql_fetch_array($res);




	
?>




<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Welcome - <?php echo $userRow['fname']; ?></title>
</head>
<body>

Hello <?php echo $userRow['fname']; ?> you are sucessfully logged in!

<br>Your last name is <?php echo $userRow['lname']; ?>
<br>Your email address is <?php echo $userRow['email']; ?>

<br><br><br><br><br><br><br><br><br><br>







<br><br><br><br><br><br><br><br><br><br>


<a href="logout.php?logout"></span>Sign Out</a></li>


<br>
<br>
<a href="register.php">Register</a> <a href="index.php">Sign in</a> <a href="admin.php">Admin</a>
             
</body>
</html>
<?php ob_end_flush(); ?>

admin.php

<?php
	ob_start();
	session_start();

	require_once 'dbconnect.php';

	
	
	// if session is not set this will redirect to login page
	if( !isset($_SESSION['user']) ) {
		header("Location: index.php");
		exit;
	}

	// select loggedin users detail
	$res=mysql_query("SELECT * FROM project WHERE id=".$_SESSION['user']);
	$userRow=mysql_fetch_array($res);




	
?>




<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Welcome - <?php echo $userRow['fname']; ?></title>
</head>
<body>


Hello <?php echo $userRow['fname']; ?> you are sucessfully logged in!

<br>Your last name is <?php echo $userRow['lname']; ?>
<br>Your email address is <?php echo $userRow['email']; ?>

<br><br><br><br><br><br><br><br><br><br>


<h1><?php echo $userRow['userlevel']; ?></h1>





<br><br><br><br><br><br><br><br><br><br>


<a href="logout.php?logout"></span>Sign Out</a></li>

<br>
<br>
<a href="register.php">Register</a> <a href="index.php">Sign in</a> <a href="admin.php">Admin</a>
             
</body>
</html>
<?php ob_end_flush(); ?>

If someone can tell me how to make the session look to the userlevel row in the DB to pull the stored info (0 or 1 for user or admin) and also how to alter the index.php (login) page accordingly, and how to edit admin.php to only allow logged in users with userlevel 1 to view the page?

Sorry if this is vague or all over the place, i am still only finding out new stuff each day

Thanks



Solution 1:[1]

If you add an is_admin field to your project table (which I assume is your users table), then you could test if the user is admin with something like below:

$sql = "SELECT * FROM project WHERE id='" . mysql_real_escape_string($id) . "'";
$res = mysql_query($sql);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if (!$row || !$row['is_admin']) {
    die();
} 

(I don't use PHP and haven't tested this code, so think of it as pseudocode)

Solution 2:[2]

WARNING

You shouldnt use the mysql_* functions in PHP anymore as they have already been removed from php7 and will not return from what I understand.

Use mysqli_* or pdo* instead.

That being said...


As for your solution to storing Database information into a user's session, you can use a couple of functions that I wrote up for just that very reason.

NOTE : These use the unsupported mysql_* functions, and should not be copy/pasted without updating to a supported alternative like mysqli_*.


Connect to a MySQL DB

function SQL_LOGIN() {
    $servername = "localhost";
    $username = "myusername";
    $password = "XXXXXXXXXX";

    // Create connection
    $conn = mysql_connect($servername, $username, $password);

    // Check connection
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }   
    return $conn;
}

-

PERFORM A MySql Lookup

function SQL_SELECT($inputDB, $inputTable, $inputColumns, $inputParams, $inputConnection) {
    $query = "SELECT ".mysql_real_escape_string($inputColumns)." from ".$inputDB.".".mysql_real_escape_string($inputTable)." ".$inputParams."";
    $result = mysql_query($query, $inputConnection);
    return $result;
}

-

Convert a SQL Query Result into an Array

function SQL_RESULT_TO_ARRAY($result) {
    $endArray = array();
    if (mysql_num_rows($result) > 0) {
        while($row = mysql_fetch_assoc($result)) {
            $endArray[] = $row;
        }
    } else {
        /* blank result */
    }    
    return $endArray;
}

-

Set Session Variable is_admin to true if user is an admin

       $inputEmail = ""; /* put in your code to get the user's email or whatever */

        session_start();
        $conn = SQL_LOGIN();

        $result = SQL_SELECT("users", "ID,EMAIL,IS_ADMIN", "where EMAIL like '".$inputEmail."'", $conn);
        $resultArray = SQL_RESULT_TO_ARRAY($result);
        foreach ($resultArray as $idx=>$childArray) {
           if ($childArray["IS_ADMIN"] == 1) { 
               $_SESSION["IS_ADMIN"] = true; 
           }
        }

EDIT

Once you set a session variable like $_SESSION["IS_ADMIN"] to true, then it will remain until:

  • you call session_destroy()
  • the user deletes the cookie from their browser
  • the session expires based on the session expiration time defined in php.ini
  • a new page is visited but the session_start() command is not called (once session_start() is called, then the session will be restored, bringing any $_SESSION[] variables along with it)

NOTE the code presented is meant to be a guide in the right direction, not a secure solution. There are parts of the code which can potentially allow for attackers to hack into your SQL database, into PHP, and even into your server.

DO NOT COPY/PASTE DIRECTLY TO PRODUCTION ENVIRONMENT

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bemmu
Solution 2