I am logging in users via windows authentication and then storing that user's rights in a session variable. I use a delimited method of rights storage in a database i.e:
$rights //retrieved from database
= 'read,edit,delete,admin'
so my question is should I;
//generate variable
$_SESSION['userrights'] = $rights ($rights is retrieved from database)
//use strpos to find if right is allowed
if (strpos($_SESSION['userrights'],"admin") !== false) { // do the function }
OR
//make array of rights
$_SESSION['userrights'] = explode(',',$rights)
//use in_array to find if right is allowed
if (in_array("admin",$_SESSION['userrights'])) { // do the function }
Bit of a OCD question as I presume the difference will be pretty much negligible for what I am doing but which would be the faster (use less resources) method?
Any answers appreciated except ones that insult my method of rights storage!
A benchmark that proofs that
strpos
is not the fastest method, but faster thanin_array
:Result:
As you can see it is important not to flip an array on-the-fly to benefit from
isset
.strpos is the fastest way to search a text needle, php.net site:
Have you considered the possibility of doing a query on the database if
$_SESSION['userrights']
exists in the database? You're already doing a query to get the list of rights in your example, why not do a query for a specific$_SESSION['userrights']
and check if there are any rows returned?As I often work with large datasets, I'd go with
isset
or!empty
on an associative array and check for the key, like @Barmar suggests. Here is a quick 1M benchmark on an Intel® Core™ i3-540 (3.06 GHz)The winner is
isset
: