What's best? Many small session values or one large one? PHP
I have about 15-20 permission settings that are loaded when a user logs in. These are each stored as a session with a value of 1 or 0.
I'm wondering, would it be better to have one session like $_SESSION['permissions']
with a value of: dothis:0,dotha开发者_运维技巧t:1,doanother:1
, etc. (one large string) which I can explode and seperate later on with PHP, or would it be best to have all these as separate sessions with just a value of 1 or 0?
Rather than a string to parse, store them as an array in $_SESSION
. This makes it much easier to modify individual permissions without having to do piles of string operations.
session_start();
$_SESSION['permissions'] = array();
$_SESSION['permissions']['dothis'] = TRUE;
$_SESSION['permissions']['dothat'] = FALSE;
$_SESSION['permissions']['doanother'] = TRUE;
Addendum
You might have figured this out already, but I thought I would add that it is easiest to interact with these via a few tiny functions. These will save a lot of typing (and typing errors), and make sure the values all end up as booleans.
function grant($permission) {
$_SESSION['permissions'][$permission] = TRUE;
}
function revoke($permission) {
$_SESSION['permissions'][$permission] = FALSE;
}
// Test if the user is allowed to do $permission
// FALSE if the permission isn't set
function user_can($permission) {
return isset($_SESSION['permissions'][$permission]) ? $_SESSION['permissions'][$permission] : FALSE;
}
The you can just call them as:
grant('dothis');
revoke('dothat');
if (user_can('doanother')) {
// congratulations you're allowed
}
I'd have an associative array that held all the permissions...
$_SESSION['permissions'] = array(
...
);
精彩评论