Click to See Complete Forum and Search --> : Page permissions
I have a page, index.php. On this page, different content is shown passed on the ?page=x parameter. X is a number, which is the id of the page to be shown. The page to be shown is stored in a MYSQL database and is included via a query.
There are three user levels, 1 2 and 3 which are defined in userlevel.
Some pages I want to show to one user level, others I want to show to a combination of user levels, for instance only level 2, or level 1 and 2.
What is the best way to store what user levels can view a particular page in my mysql database (where there are only two columns – pageid and content)?
maveruk
08-01-2008, 09:39 AM
Set a field in the table called "access_rights" or something. Set it to text.
Then set "[1]" for level 1, [2][3] for 2 and 3 on each page.
$_SESSION['level'] = 2
That way you can do... "SELECT... FROM... WHERE access_rights LIKE '%[" . $_SESSION['level'] . "]%' and only get the page that user is able to access. If no result turns up, you can say the page either doesn't exist or they don't have permission.
Since the level is 2, user level 2 and 3 can read the same page.
The reason I put them in [] is because if your level is 2, and you allow level 12 access to the page, it will allow level 2 access because it contains 2. Adding [] around it makes it a distinct value.
If you want to verify a specific message: "SELECT access_rights FROM .... "
Then check if that contains your level by doing a match on "[" . $_SESSION['level'] . "]"; No match, output the message "You don't have permission. Go Back";
If there were no results at all, you can do "The page could not be found";
What you can also do is [P], which is the level for people who are "public", so visitors who don't have an access level can view the pages. Just set $_SESSION['P'] when they aren't logged in.
Example users table
userid name password level
123 bob bananaz 1
789 sam pearz 3
456 dom applez 2
After login store the userid in a SESSION variable
At the top of each page you want to secure add a function call with the level passed in.
<?
permissioncheck(2);
//only sam and dom can see this page
?>
The function is placed in a file to be included across all pages that need checking
<?
function permissioncheck($level){
$userslevel=mysql_result(mysql_query("SELECT level FROM users WHERE userid=".$_SESSION['userid']),0,0);
if($userslevel>=$level){
//level is equal to or greater than required for the page
//display page contents
}else{
//level is too low
//display denied message
}
}
If you want to store the level for each page then the level in the function call and look up the script name and level in the function and check in the same way.
script table
scriptname level
/path/to/file/intro.php 1
/path/to/file/secret.php 3
Another way of doing it would be to join the two tables on levels where script name equals the current script and see if your user's id is in the list by looping through the results.