I am working on a web-app system that has multiple apps, each with a Primary Key to identify them. Each user also has a security level tied to an app, for instance App #1 with a security level of 5. I want to store all the app / security information in the database as a token, and then retrieve that information to store it in Session.
So given the following apps:
and a user that has security level 3, 5, and 7 respectively, the token will be stored as:
1.3|2.5|3.7.
My question is, how do I retrieve that data in a usable form? I was thinking of having it in an array, with the array key of the App ID, like somearray[1] = 3
, somearray[2] = 5
, etc, but I have no idea how to handle this.
I'm early in development on this part, so I have a very open mind towards suggestions. Thanks in advance for the help.
the token will be stored as:
1.3|2.5|3.7.
Why don't you store security levels in a database ? It will be much more easy to manage. I could imagine few tables like the following:
App
--------
id
name
....
Users
--------
id
name
email
...
App_users_permissions
--------
id
app_id (references App.id)
user_id (references Users.id)
level
Then, you could do a simple query like:
SELECT level FROM App_users_permissions WHERE user_id = 1 AND app_id = 2
This query would then return the current previlege id, for a given app id and user id.
I think that would be the easiest way to manage this.
you you really want to store this things as one string (you shouldn't), you could use explode() to take it apart again.
anyway, the much better solution would be to properly normalize your database (step-to-step guide for this).
You should really redesign your database as suggested by Pierre-Olivier Bourgeois.
If you want to stick with the described format, you could use preg_match_all()
:
$subject = '1.3|2.5|3.7.';
$pattern = '=(\d+)\.(\d+)=';
$result = preg_match_all($pattern, $subject, $subpattern, PREG_SET_ORDER);
foreach ($subpattern as $match) {
$out[$match[1]] = $match[2];
}
print_r($out);
Explode
Item = explode('|',token);
List(key,val) = explode('.',Item);
Echo List, val